Make a Positive Array - Problem

You are given an integer array nums. Your goal is to transform this array into a positive array using the minimum number of operations possible.

An array is considered positive if every subarray with more than two elements has a positive sum. In other words, for any subarray nums[i...j] where j - i + 1 > 2, the sum of all elements in that subarray must be greater than 0.

Operation: You can replace any element in the array with any integer between -1018 and 1018.

Your task: Find the minimum number of operations needed to make the array positive.

Example: For array [1, -5, 2, -3], the subarray [1, -5, 2] has sum -2 (negative), and [-5, 2, -3] has sum -6 (negative). We need to fix these violations with minimum operations.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, -5, 2, -3]
โ€บ Output: 2
๐Ÿ’ก Note: The subarray [1, -5, 2] has sum -2 (negative), and [-5, 2, -3] has sum -6 (negative), and [1, -5, 2, -3] has sum -5 (negative). We need to modify at least 2 elements to make all subarrays of length 3+ positive.
example_2.py โ€” Already Positive
$ Input: nums = [5, 3, 1, 2]
โ€บ Output: 0
๐Ÿ’ก Note: All subarrays with length 3+ already have positive sums: [5,3,1]=9, [3,1,2]=6, [5,3,1,2]=11. No operations needed.
example_3.py โ€” Small Array
$ Input: nums = [-1, -2]
โ€บ Output: 0
๐Ÿ’ก Note: Array has only 2 elements, so no subarrays with more than 2 elements exist. The array is already positive by definition.

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • -1018 โ‰ค nums[i] โ‰ค 1018
  • At least 60% of subarrays must have length > 2
  • Replacement values must be between -1018 and 1018

Visualization

Tap to expand
Tank 1: -2Tank 2: +5Tank 3: -1Tank 4: +3Sea Level (0)Sequence [1,2,3]: -2 + 5 + (-1) = 2 โœ“Sequence [2,3,4]: 5 + (-1) + 3 = 7 โœ“All 4-tank sequence: -2 + 5 + (-1) + 3 = 5 โœ“Strategy: Greedy AdjustmentAdjust rightmost tank in eachnegative sequence first
Understanding the Visualization
1
Initial Setup
We have tanks with different water levels, some negative (below sea level)
2
Check Sequences
We check every sequence of 3+ tanks to see if total water is positive
3
Strategic Adjustments
When we find negative totals, we add water to the rightmost tank to fix multiple sequences at once
4
Optimal Result
Continue until all sequences have positive totals with minimum adjustments
Key Takeaway
๐ŸŽฏ Key Insight: By adjusting the rightmost element in each violating subarray, we can fix multiple overlapping subarrays simultaneously, leading to the minimum number of operations.
Asked in
Google 42 Amazon 38 Meta 29 Microsoft 25
28.4K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen