你能构造出连续值的最大数目【LC1798】
You are given an integer array
coinsof lengthnwhich represents thencoins that you own. The value of theithcoin iscoins[i]. You can make some valuexif you can choose some of yourncoins such that their values sum up tox.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.
滑雪去了 漏了两天 明天补!
-
思路【贪心】
- 局部最优:每次从数组中找到未选择数字中的最小值来更新区间,如果当前连续值xxx小于选择的数值coincoincoin,那么无法获得更大的区间,退出循环
- 当前区间为[0,x][0,x][0,x],选择数值coincoincoin后获得的数值和的区间范围是[coin,x+coin][coin,x+coin][coin,x+coin],只有当这两个区间有交集或连续时,才能更新结果,此时的条件为x≥coin−1x \ge coin - 1x≥coin−1
- 全局最优:能构造出连续值的最大数目最大
- 局部最优:每次从数组中找到未选择数字中的最小值来更新区间,如果当前连续值xxx小于选择的数值coincoincoin,那么无法获得更大的区间,退出循环
-
实现:将数组从小到大排序,构造出连续值的最大数目
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(n)O(n)
- 空间复杂度:O(1)O(1)O(1)
- 复杂度

该问题是一个关于数组处理的编程挑战,目标是通过已有的硬币面值构造出最大的连续整数序列。采用贪心算法,先对硬币面值进行排序,然后尝试从小到大选择硬币,如果当前选择的硬币面值大于当前连续序列的最大值,则结束选择,最后返回连续序列的长度。
16万+

被折叠的 条评论
为什么被折叠?



