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: Subarrays with length ≥ 3: [-5, 2, -3] has sum -6 ≤ 0, [2, -3, 1] has sum 0 ≤ 0, and [-5, 2, -3, 1] has sum -5 ≤ 0. Replace nums[1] = 2 with a large positive number. This makes [-5, X, -3] positive, [X, -3, 1] positive, and [-5, X, -3, 1] positive. So 1 operation is needed.
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 - Greedy Approach INPUT Array nums: -5 [0] 2 [1] -3 [2] 1 [3] Subarrays (size > 2): [-5,2,-3] sum=-6 (BAD) [2,-3,1] sum=0 (BAD) [-5,2,-3,1] sum=-5 (BAD) All subarrays must have positive sum! n = 4 elements ALGORITHM STEPS 1 Identify Problem Find negative sum subarrays 2 Greedy Choice Replace element affecting most bad subarrays 3 Replace -3 at [2] Change -3 to large positive Replacement: Before: [-5, 2, -3, 1] After: [-5, 2, 10, 1] 4 Verify Result Check all subarrays now have positive sums Operations: 1 FINAL RESULT Modified Array: -5 2 10 1 Verified Subarrays: [-5,2,10] = 7 (OK) [2,10,1] = 13 (OK) [-5,2,10,1] = 8 (OK) OUTPUT 1 Minimum operations to make array positive Array is now POSITIVE! Key Insight: The greedy strategy identifies which element appears in the most "bad" subarrays (negative sum). Replacing that element with a large positive value fixes multiple subarrays at once, minimizing operations. Here, replacing -3 with 10 fixes all three failing subarrays in just ONE operation. TutorialsPoint - Make a Positive Array | Greedy Replacement Strategy
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