From d39ecf28a88b210ca4c2cd39265351f8528f53f7 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Sat, 11 Jun 2022 12:44:55 +0100 Subject: [PATCH] minimum-operations-to-reduce-x-to-zero --- minimum-operations-to-reduce-x-to-zero/sol.rs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 minimum-operations-to-reduce-x-to-zero/sol.rs diff --git a/minimum-operations-to-reduce-x-to-zero/sol.rs b/minimum-operations-to-reduce-x-to-zero/sol.rs new file mode 100644 index 0000000..03f0363 --- /dev/null +++ b/minimum-operations-to-reduce-x-to-zero/sol.rs @@ -0,0 +1,23 @@ +impl Solution { + pub fn min_operations(nums: Vec, x: i32) -> i32 { + let target_diff = nums.iter().sum::() - 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 + } + } +} \ No newline at end of file