【每日一题Day58】LC1785构成特定和添加的最少元素 | 贪心

构成特定和添加的最少元素【LC1785】

You are given an integer array nums and two integers limit and goal. The array nums has an interesting property that abs(nums[i]) <= limit.

Return the minimum number of elements you need to add to make the sum of the array equal to goal. The array must maintain its property that abs(nums[i]) <= limit.

Note that abs(x) equals x if x >= 0, and -x otherwise.

2022/12/16
LC1827最少操作数使数组递增这题很类似,还更简单些

  • 思路:首先统计数组nums的和sum,然后计算sumgoal的差target,我们需要向数组中添加最少的元素,使元素的和满足差值,元素的个数即为最终结果,因此每次添加的元素应尽可能最大。由于添加数值的绝对值大小受limit限制,因此添加元素的数值绝对值为limit的个数为 M a t h . a b s ( t a r g e t ) / l i m i t Math.abs(target) / limit Math.abs(target)/limit,如果 M a t h . a b s ( t a r g e t ) Math.abs(target) % limit Math.abs(target)不等于0,那么还需添加一个元素使和等于target

    【贪心】

    • 局部最优:每次添加的元素应尽可能最大
    • 全局最优:添加的元素个数最少
  • 实现

    为了防止越界使用long类型变量存储target

    class Solution {
        public int minElements(int[] nums, int limit, int goal) {
            long target = (long) goal;
            int count = 0;
            for (long num : nums){
                target -= num;
            }
            count += Math.abs(target) / limit;       
            return Math.abs(target) % limit == 0 ? count : count + 1;
    
        }
    }
    
    • 复杂度
      • 时间复杂度: 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、付费专栏及课程。

余额充值