Given an integer array nums, you can modify any element to any value you choose.
Return the minimum number of elements you need to modify so that every subarray of length greater than 1 has a non-negative sum. A subarray is a contiguous non-empty sequence of elements within the array.
Function Signature
def min_modifications(nums: list[int]) -> int:
Rules
-
A modification replaces one element with any integer. There is no bound on the new value.
-
Only subarrays with at least 2 elements must have a sum of 0 or more. A single element may stay negative.
-
Return only the number of modified elements.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [1,-3,2,-1,5]
Output: 1
The negative subarrays [1,-3], [-3,2], [-3,2,-1] and [1,-3,2,-1] all contain the -3, so changing that one element (for example to 0, giving [1,0,2,-1,5]) fixes all of them. Zero changes is not enough because [1,-3] sums to -2.
Input: nums = [-5,-3,-2,-4]
Output: 2
Any two of these values sum to a negative number, so two adjacent positions cannot both keep their values, and keeping three of the four positions always leaves an adjacent pair. Changing -3 to 7 and -4 to 2 gives [-5,7,-2,2], where every subarray of length at least 2 sums to 0 or more.
Input: nums = [-1,1,-1]
Output: 1
Both adjacent pairs sum to 0, but the whole array sums to -1, so at least one element must change. Changing the last element to 10 gives [-1,1,10], whose subarrays of length at least 2 sum to 0, 11 and 10.