你能构造出连续值的最大数目【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 )