Similar Problems
Similar Problems not available
Minimum Operations To Reduce X To Zero - Leetcode Solution
Companies:
LeetCode: Minimum Operations To Reduce X To Zero Leetcode Solution
Difficulty: Medium
Topics: hash-table binary-search sliding-window array prefix-sum
Problem:
You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1.
Solution:
We can solve the problem using a two-pointer approach. First, we calculate the sum of all elements in the array, and then we move two pointers from the beginning of the array until we find a subarray whose sum is equal to the target sum x. Then we move the left pointer to the end of the subarray and continue the search. We keep track of the minimum length of the subarray and return it as the answer.
Algorithm:
- Calculate the sum of all elements in the array.
- Check if the sum is less than the target x. If it is, return -1.
- Initialize two pointers
left
andright
at the beginning of the array. - Initialize a variable
subarray_sum
as 0. - Run a loop until the
subarray_sum
is greater than or equal tox
. a. Ifsubarray_sum
is equal tox
, update the answer with the length of the subarray and moveleft
pointer to the next element. b. Ifsubarray_sum
is less thanx
, add the value ofnums[right]
tosubarray_sum
and moveright
pointer to the next element. c. Ifsubarray_sum
is greater thanx
, subtract the value ofnums[left]
fromsubarray_sum
and moveleft
pointer to the next element. - Return the minimum length of the subarray. If it is equal to
nums.len() + 1
, return -1.
Code:
impl Solution {
pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 {
let sum = nums.iter().sum::<i32>();
let target = sum - x;
let mut left = 0;
let mut subarray_sum = 0;
let mut answer = nums.len() + 1;
for (right, &num) in nums.iter().enumerate() {
subarray_sum += num;
while subarray_sum > target && left <= right {
subarray_sum -= nums[left];
left += 1;
}
if subarray_sum == target {
answer = answer.min(nums.len() - right + left - 1);
}
}
if answer > nums.len() {
-1
} else {
answer as i32
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Minimum Operations To Reduce X To Zero Solution Code
1