构成特定和添加的最少元素【LC1785】
You are given an integer array
nums
and two integerslimit
andgoal
. The arraynums
has an interesting property thatabs(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 thatabs(nums[i]) <= limit
.Note that
abs(x)
equalsx
ifx >= 0
, and-x
otherwise.
2022/12/16
跟LC1827最少操作数使数组递增这题很类似,还更简单些
-
思路:首先统计数组
nums
的和sum
,然后计算sum
与goal
的差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)
- 复杂度