647. Make the Prefix Sum Non-negative
An integer array nums with a 0-index is provided to you. You can use the following operation as many times as you like:
- Choose any element from the list of numbers and add it at the end.
The prefix sum array of nums is an array prefix of the same length as nums such that prefix[i] is the sum of all the integers nums[j] where j is in the inclusive range [0, i].
Return the bare minimum of operations required to ensure that there are no negative numbers in the prefix sum array. The prefix sum array can always be made non-negative thanks to the manner the test cases are created.
Example 1:
Input : nums = [1, 2, 3, 4, 5]
Output : 0
Explanation :
Prefix sum array = [1, 3, 6, 10, 15]
As the prefix sum array does not contain any negative elements, so no operations are required.
Example 2:
Input : nums = [5, -7, 3, -1, 0]
Output : 1
Explanation :
Prefix sum array = [5, -2, 1, 0, 0].
The Prefix Sum becomes negative at index 1. So with the operation we will move element at index 1 (-7) at end of array.
New array = [5, 3, -1, 0, -7]
New Prefix Sum = [5, 8, 7, 7, 0]. New prefix sum array does not contain any negative element.
So total number of operations = 1.
Now Your Turn!
Pick the correct output for the given inputInput : [5, -5, -7, 8, 4]
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= n <= 105
- -109 <= nums[i] <= 109
- The testcase are generated so that it is always possible to form a array with non negative prefix sum.