|
| 1 | +/** |
| 2 | + * [1785] Minimum Elements to Add to Form a Given Sum |
| 3 | + * |
| 4 | + * 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. |
| 5 | + * 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. |
| 6 | + * Note that abs(x) equals x if x >= 0, and -x otherwise. |
| 7 | + * |
| 8 | + * Example 1: |
| 9 | + * |
| 10 | + * Input: nums = [1,-1,1], limit = 3, goal = -4 |
| 11 | + * Output: 2 |
| 12 | + * Explanation: You can add -2 and -3, then the sum of the array will be 1 - 1 + 1 - 2 - 3 = -4. |
| 13 | + * |
| 14 | + * Example 2: |
| 15 | + * |
| 16 | + * Input: nums = [1,-10,9,1], limit = 100, goal = 0 |
| 17 | + * Output: 1 |
| 18 | + * |
| 19 | + * |
| 20 | + * Constraints: |
| 21 | + * |
| 22 | + * 1 <= nums.length <= 10^5 |
| 23 | + * 1 <= limit <= 10^6 |
| 24 | + * -limit <= nums[i] <= limit |
| 25 | + * -10^9 <= goal <= 10^9 |
| 26 | + * |
| 27 | + */ |
| 28 | +pub struct Solution {} |
| 29 | + |
| 30 | +// problem: https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/ |
| 31 | +// discuss: https://leetcode.com/problems/minimum-elements-to-add-to-form-a-given-sum/discuss/?currentPage=1&orderBy=most_votes&query= |
| 32 | + |
| 33 | +// submission codes start here |
| 34 | + |
| 35 | +impl Solution { |
| 36 | + pub fn min_elements(nums: Vec<i32>, limit: i32, goal: i32) -> i32 { |
| 37 | + let mut temp = 0isize; |
| 38 | + |
| 39 | + for v in nums { |
| 40 | + temp += v as isize; |
| 41 | + } |
| 42 | + |
| 43 | + let diff = temp - goal as isize; |
| 44 | + let result = diff / limit as isize; |
| 45 | + |
| 46 | + (if diff % limit as isize != 0 { |
| 47 | + result.abs() + 1 |
| 48 | + } else { |
| 49 | + result.abs() |
| 50 | + }) as i32 |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +// submission codes end |
| 55 | + |
| 56 | +#[cfg(test)] |
| 57 | +mod tests { |
| 58 | + use super::*; |
| 59 | + |
| 60 | + #[test] |
| 61 | + fn test_1785_example_1() { |
| 62 | + let nums = vec![1, -1, 1]; |
| 63 | + let limit = 3; |
| 64 | + let goal = -4; |
| 65 | + |
| 66 | + let result = 2; |
| 67 | + |
| 68 | + assert_eq!(Solution::min_elements(nums, limit, goal), result); |
| 69 | + } |
| 70 | + |
| 71 | + #[test] |
| 72 | + fn test_1785_example_2() { |
| 73 | + let nums = vec![1, -10, 9, 1]; |
| 74 | + let limit = 100; |
| 75 | + let goal = 0; |
| 76 | + |
| 77 | + let result = 1; |
| 78 | + |
| 79 | + assert_eq!(Solution::min_elements(nums, limit, goal), result); |
| 80 | + } |
| 81 | +} |
0 commit comments