Make a Positive Array - Problem

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 nums with any integer between -10¹⁸ and 10¹⁸.

Find the minimum number of operations needed to make nums positive.

Input & Output

Example 1 — Basic Negative Array
$ Input: nums = [-5, 2, -3, 1]
Output: 1
💡 Note: Subarray [-5, 2, -3] has sum -6 ≤ 0 and subarray [2, -3, 1] has sum 0 ≤ 0. Replace nums[0] = -5 with a large positive number to fix both problems with 1 operation.
Example 2 — Already Positive
$ Input: nums = [1, 2, 3]
Output: 0
💡 Note: The only subarray with length ≥ 3 is [1, 2, 3] with sum 6 > 0. Array is already positive, so 0 operations needed.
Example 3 — Multiple Problems
$ Input: nums = [-2, -3, -1, -4, 1]
Output: 2
💡 Note: Multiple negative subarrays exist. Replace the two most impactful negative elements (like nums[1] = -3 and nums[3] = -4) to make all subarrays positive with 2 operations.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -1018 ≤ nums[i] ≤ 1018
  • You can replace any element with any integer between -1018 and 1018

Visualization

Tap to expand
Make a Positive Array: Strategic Element Replacement-52-31Original Array: [-5, 2, -3, 1]Subarray [-5,2,-3]: sum = -6 ≤ 0Subarray [2,-3,1]: sum = 0 ≤ 0⬇ Replace -5 with large positive value ⬇1e92-31Result: All subarrays length ≥ 3 now have positive sum✓ 1 operation needed
Understanding the Visualization
1
Input Analysis
Array with negative subarrays that need fixing
2
Identify Problems
Find all subarrays length ≥ 3 with sum ≤ 0
3
Strategic Replacement
Replace minimum elements to make all subarrays positive
Key Takeaway
🎯 Key Insight: Greedily replace elements that contribute to the most negative subarrays to minimize total operations needed.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 25
28.4K Views
Medium Frequency
~35 min Avg. Time
892 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