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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

  • 思路【贪心】

    • 局部最优:每次从数组中找到未选择数字中的最小值来更新区间,如果当前连续值xxx小于选择的数值coincoincoin,那么无法获得更大的区间,退出循环
      • 当前区间为[0,x][0,x][0,x],选择数值coincoincoin后获得的数值和的区间范围是[coin,x+coin][coin,x+coin][coin,x+coin],只有当这两个区间有交集或连续时,才能更新结果,此时的条件为x≥coin−1x \ge coin - 1xcoin1
    • 全局最优:能构造出连续值的最大数目最大
  • 实现:将数组从小到大排序,构造出连续值的最大数目

    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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值