835. Positive Array Formation

Given an array nums of size n.

An array is positive if the sum of every subarray with a length greater than two is strictly positive.

You may perform the following operation: Choose any index i and replace nums[i] with any number between -1018 and 1018.

Return the minimum number of operations required to make nums positive.

Example 1:

Input: nums = [-10, 15, -12]

Output: 1

Explanation: The only subarray with more than 2 elements is [-10, 15, -12]. Its sum is -10 + 15 + (-12) = -7, which is not positive.

By replacing nums[0] with 0, the array becomes [0, 15, -12].

The new sum is 0 + 15 + (-12) = 3, which is positive. Only 1 operation was needed.

Example 2:

Input: nums = [-1, -2, 3, -1, 2, 6]

Output: 1

Explanation: Initially, there are three subarrays with a length greater than 2 that have a sum of 0 or less:

  1. nums[0...2]: [-1, -2, 3] → Sum = 0
  2. nums[0...3]: [-1, -2, 3, -1] → Sum = -1
  3. nums[1...3]: [-2, 3, -1] → Sum = 0

By replacing nums[1] with 1, the array becomes [-1, 1, 3, -1, 2, 6].

The new sums for those specific subarrays are now:

  • nums[0...2]: -1 + 1 + 3 = 3
  • nums[0...3]: -1 + 1 + 3 + (-1) = 2
  • nums[1...3]: 1 + 3 + (-1) = 3

Since all subarrays with more than two elements now have a positive sum, the minimum number of operations is 1.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1,2,3,-5,3]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  1. 3 <= nums.length <= 105
  2. -109 <= nums[i] <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
int positiveArrayFormation(vector<int>& nums) {
// Your code goes here
}
};
 
Test Case

Input:

Nums