Skip to content

Commit e4b5e58

Browse files
committed
1785. Minimum Elements to Add to Form a Given Sum: AC
1 parent b1a5fb3 commit e4b5e58

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1345,3 +1345,4 @@ mod s1780_check_if_number_is_a_sum_of_powers_of_three;
13451345
mod s1781_sum_of_beauty_of_all_substrings;
13461346
mod s1782_count_pairs_of_nodes;
13471347
mod s1784_check_if_binary_string_has_at_most_one_segment_of_ones;
1348+
mod s1785_minimum_elements_to_add_to_form_a_given_sum;
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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

Comments
 (0)