#1785
Medium Algorithms Minimum elements to add to form a given sum
Array Greedy
45.0% acceptance
Feb 25, 2026
284
196
You are given an integer array nums and two integers limit and goal. The array nums has property abs(nums[i]) <= limit.
Return the minimum number of elements you need to add to make the sum equal to goal. Each added element must also satisfy abs(x) <= limit.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_elements(nums: Vec<i32>, limit: i32, goal: i32) -> i32 {
let sum: i64 = nums.iter().map(|&x| x as i64).sum();
let diff = (goal as i64 - sum).abs();
let limit = limit as i64;
((diff + limit - 1) / limit) as i32
}
}