minimum-operations-to-reduce-x-to-zero

This commit is contained in:
Gleb Koval 2022-06-11 12:44:55 +01:00
parent 246fbade63
commit d39ecf28a8
Signed by: cyclane
GPG Key ID: 15E168A8B332382C
1 changed files with 23 additions and 0 deletions

View File

@ -0,0 +1,23 @@
impl Solution {
pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 {
let target_diff = nums.iter().sum::<i32>() - x;
let (mut l, mut current, mut max) = (0, 0, 0);
let mut found = false;
for r in 0..nums.len() {
current += nums[r];
while l <= r && current > target_diff {
current -= nums[l];
l += 1;
}
if current == target_diff {
max = max.max(r - l + 1);
found = true;
}
}
if found {
(nums.len() - max) as i32
} else {
-1
}
}
}