Minimum Operations to Reduce X to Zero
Take numbers from either end of an array until they add up to x, using as few as possible.
Given an array of positive integers numsxxx
Example 1
Output: 2
Explanation: remove the last two numbers, 3 and 2.
Example 2
Output: -1
Example 3
Output: 5
Explanation: remove the first two numbers and the last three.
The Idea
Picture six cards in a row: 3, 2, 20, 1, 1 and 3, as in Example 3. You may only take a card from one of the two ends of the row. You want the cards you take to add up to exactly 10, and you want to take as few cards as possible.
The 20 is the problem. Taking it already goes past 10, so the whole 10 must come from the cards around it. Taking 3 and 2 from the left gives 5, and taking 1, 1 and 3 from the right gives the other 5. That is five cards, the answer to Example 3.
In a longer row there are many ways to split the cards between the two ends: none from the left and some from the right, one from the left, two from the left, and so on. Each split needs its own count from the right. How can we find the best split without trying them all?
Look at what stays behind instead of what is taken. Whatever we take from the two ends, the cards that are left always sit next to each other in one unbroken stretch in the middle. Look at the picture below.
The two cards marked "removed from the left" add up to 5, and the three marked "removed from the right" add up to 5 too. The orange box, the "kept middle", holds 20. All six cards add up to 30, and since the removed cards make 10, the kept middle must make 30 - 10 = 20.
That holds for every array. The kept middle always adds up to the total minus xx
Solution Approach
Turning that idea into code means settling three things: what sum the middle must have, how to find the longest middle with that sum, and how to tell an empty middle apart from no middle at all.
The sum the middle must have
What should the kept middle add up to? Call it targettotalxxtarget
If targetx
Finding the longest middle
How do we find the longest stretch with sum target
A faster way uses two markers, leftrightrighttargetleftleft
Why is it safe to move leftleft
Follow Example 3, where target
An empty middle
What if xtarget
So a length of 0 is a real answer. The value that means "no middle found yet" has to be something else, and -1 works, because no stretch has a negative length.
Java Solution
The method minOperations
- First, add up every number with a for-each loop into
.total - Compute
, the sum the kept middle must have. If it is negative, return -1.target = total - x - Set up the window:
starts at 0, the window'sleft at 0, andsum at -1, meaning no middle found yet.longest - A for loop moves
over the array and addsright tonums[right] . Inside it, a while loop subtractssum and movesnums[left] forward for as long asleft is bigger thansum .target - When
equalssum , the numbers fromtarget toleft form a valid middle, and its lengthright replacesright - left + 1 if it is bigger.longest - After the loop, return -1 if
is still -1. Otherwise returnlongest , the number of removed numbers.nums.length - longest
The mainxx
public class MinOperationsToReduceXToZero {
public static int minOperations(int[] nums, int x) {
int total = 0;
for (int v : nums) {
total += v;
}
int target = total - x; // what the untouched middle part must sum to
if (target < 0) {
return -1;
}
int left = 0;
int sum = 0;
int longest = -1; // longest middle part with sum == target
for (int right = 0; right < nums.length; right++) {
sum += nums[right];
while (sum > target) {
sum -= nums[left];
left++;
}
if (sum == target) {
longest = Math.max(longest, right - left + 1);
}
}
return longest == -1 ? -1 : nums.length - longest;
}
public static void main(String[] args) {
System.out.println(minOperations(new int[] {1, 1, 4, 2, 3}, 5));
System.out.println(minOperations(new int[] {5, 6, 7, 8, 9}, 4));
System.out.println(minOperations(new int[] {3, 2, 20, 1, 1, 3}, 10));
System.out.println(minOperations(new int[] {2, 3, 1, 1, 1}, 5));
System.out.println(minOperations(new int[] {1, 2, 3}, 6));
System.out.println(minOperations(new int[] {1, 2, 3}, 7));
}
}
Running it prints:
2
-1
5
2
3
-1
The answers 2, -1 and 5 match the three examples. In Example 1 the total is 11, so the kept middle must add up to 11 - 5 = 6. That is 1, 1, 4, three of the five numbers, so two numbers go.
The fourth line, 2, comes from [2, 3, 1, 1, 1]x = 5[1, 2, 3]
Why does longest
The original implementation,
Complexity
The work is one pass to add up the array, then one pass of the window.
- Time: O(n), because the first loop reads each of the n numbers once,
visits each number once, andright only moves forward, so the while loop removes at most n numbers over the whole run.left - Space: O(1), because the method keeps only
,total ,target ,sum andleft , and never copies the array.longest