【每日一题Day108】LC1798你能构造出连续值的最大数目 | 贪心

简介: 局部最优:每次从数组中找到未选择数字中的最小值来更新区间,如果当前连续值x小于选择的数值coin,那么无法获得更大的区间,退出循环

你能构造出连续值的最大数目【LC1798】


You are given an integer array coins of length n which represents the n coins that you own. The value of the ith coin is coins[i]. You can make some value x if you can choose some of your n coins such that their values sum up to x.


Return the maximum number of consecutive integer values that you can make with your coins starting from and including 0.


Note that you may have multiple coins of the same value.


滑雪去了 漏了两天 明天补!


  • 思路【贪心】


。局部最优:每次从数组中找到未选择数字中的最小值来更新区间,如果当前连续值x小于选择的数值coin,那么无法获得更大的区间,退出循环


  • 当前区间为[0,x],选择数值coin后获得的数值和的区间范围是[coin,x+coin],只有当这两个区间有交集或连续时,才能更新结果,此时的条件为x≥coin−1


。全局最优:能构造出连续值的最大数目最大


  • 实现:将数组从小到大排序,构造出连续值的最大数目


class Solution {
    public int getMaximumConsecutive(int[] coins) {
        Arrays.sort(coins);
        int x = 0;
        for (int coin : coins){
            if (x < coin - 1) break;
            x += coin;
        }
        return x + 1;
    }
}


class Solution {
    public int getMaximumConsecutive(int[] coins) {
        Arrays.sort(coins);
        int res = 1;
        for (int coin : coins){
            if (res < coin) break;
            res += coin;
        }
        return res;
    }
}


。复杂度


时间复杂度:O ( n )

空间复杂度:O ( 1 )

目录
相关文章
|
5月前
【Leetcode 2645】构造有效字符串的最小插入数 —— 动态规划
状态定义:`d[i]`为将前 i 个字符拼凑成若干个 abc 所需要的最小插入数。状态转移方程: 如果` word[i]>word[i−1]`,那么`word[i]`可以和`word[i−1]`在同一组 abc 中,`d[i]=d[i−1]−1` ;否则`word[i]`单独存在于一组 abc 中,`d[i]=d[i−1]+2`
|
5月前
【每日一题Day357】LC1155掷骰子等于目标和的方法数 | dp
【每日一题Day357】LC1155掷骰子等于目标和的方法数 | dp
54 0
|
5月前
【每日一题Day118】LC1124表现良好的最长时间段 | 前缀和+单调栈/哈希表
【每日一题Day118】LC1124表现良好的最长时间段 | 前缀和+单调栈/哈希表
49 0
|
5月前
【每日一题Day159】LC1638统计只差一个字符的子串数目 | 枚举
【每日一题Day159】LC1638统计只差一个字符的子串数目 | 枚举
36 0
|
5月前
【每日一题Day163】LC2367算术三元组的数目 | 二分查找 哈希表
【每日一题Day163】LC2367算术三元组的数目 | 二分查找 哈希表
29 0
|
11月前
|
算法
【代码随想录】LC 209. 长度最小的子数组
利用两层循环,第一层循环枚举子数组的起点位置,第二层循环枚举子数组的终点位置,第二层循环中可以同时来统计当前子数组的和,如果符合题目条件则更新length,否则继续循环,直至两层循环结束,返回题目要求的值,算法结束。
51 0
|
5月前
|
Go C++
【力扣】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
【2月更文挑战第17天】2645. 构造有效字符串的最小插入数(动态规划 贪心 滚动数组优化 C++ Go)
42 8
|
5月前
|
vr&ar
【每日一题Day166】LC1053交换一次的先前排列 | 贪心
【每日一题Day166】LC1053交换一次的先前排列 | 贪心
67 1
|
5月前
【每日一题Day236】LC2475数组中不等三元组的数目
【每日一题Day236】LC2475数组中不等三元组的数目
33 0
|
5月前
【每日一题Day358】LC2698求一个整数的惩罚数 | 递归
【每日一题Day358】LC2698求一个整数的惩罚数 | 递归
50 0