minimum-operations-to-reduce-x-to-zero
This commit is contained in:
parent
246fbade63
commit
d39ecf28a8
|
@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue