Make a Positive Array Problem
Description
LeetCode Problem 3511.
You are given an array nums. An array is considered positive if the sum of all numbers in each subarray with more than two elements is positive.
You can perform the following operation any number of times:
- Replace one element in
numswith any integer between -10^18 and 10^18.
Find the minimum number of operations needed to make nums positive.
Example 1:
Input: nums = [-10,15,-12]
Output: 1
Explanation:
The only subarray with more than 2 elements is the array itself. The sum of all elements is (-10) + 15 + (-12) = -7. By replacing nums[0] with 0, the new sum becomes 0 + 15 + (-12) = 3. Thus, the array is now positive.
Example 2:
Input: nums = [-1,-2,3,-1,2,6]
Output: 1
Explanation:
The only subarrays with more than 2 elements and a non-positive sum are:
Subarray Indices Subarray Sum Subarray After Replacement (Set nums[1] = 1) New Sum
nums[0...2] [-1, -2, 3] 0 [-1, 1, 3] 3
nums[0...3] [-1, -2, 3, -1] -1 [-1, 1, 3, -1] 2
nums[1...3] [-2, 3, -1] 0 [1, 3, -1] 3
Thus, nums is positive after one operation.
Example 3:
Input: nums = [1,2,3]
Output: 0
Explanation:
The array is already positive, so no operations are needed.
Constraints:
3 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Greedy with Prefix Sums
Checking every subarray of length at least 3 would take O(n2) time, so we use prefix sums instead. A subarray nums[i..j] with j - i >= 2 has a non-positive sum exactly when the prefix sum ending at j is at most some earlier prefix sum that starts at least two positions before.
Scan from left to right and keep, for the current segment, the running sum s and preMx, the largest sum of a prefix of the segment that is at least two elements shorter than the current one (so the remaining part has at least three elements). If the current sum s is at most preMx, some subarray of length at least 3 ending here is non-positive. Replacing the element at the current position with a huge value fixes every such subarray that crosses it, so we count one operation, start a new segment right after it, and reset s and preMx. Delaying the fix to the last possible position is optimal because it covers the most subarrays.
Complexity: O(n) time and O(1) extra space.
class Solution:
def makeArrayPositive(self, nums: List[int]) -> int:
l = -1
ans = pre_mx = s = 0
for r, x in enumerate(nums):
s += x
if r - l > 2 and s <= pre_mx:
ans += 1
l = r
pre_mx = s = 0
elif r - l >= 2:
pre_mx = max(pre_mx, s - x - nums[r - 1])
return ans