Given an integer array nums, return the minimum number of element modifications needed so that the array contains no subarray of length 3 where nums[i] <= nums[i+1] <= nums[i+2].
A modification changes exactly one element to any value of your choice. After all modifications, no three consecutive elements may form a non-decreasing sequence.
Function Signature
def min_modifications(nums: list[int]) -> int:
Rules
-
A modification replaces one element with any integer. The new value does not have to lie inside the input range.
-
Three consecutive elements are non-decreasing when
nums[i] <= nums[i+1] <= nums[i+2]
, so equal neighbors count as non-decreasing.
-
Return only the count. An array with fewer than 3 elements needs 0 modifications.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [1, 2, 3, 4, 5]
Output: 2
A single change cannot work: a new nums[2] would have to be below 2 to break [1, 2, x] and above 4 to break [x, 4, 5], and changing any other index leaves [1, 2, 3] or [3, 4, 5] intact. Raising nums[1] and nums[3] to 100 gives [1, 100, 3, 100, 5], where every window contains a drop.
Input: nums = [5, 4, 3, 2, 1]
Output: 0
The array is strictly decreasing, so no window of three is non-decreasing.
Input: nums = [3, 1, 2, 2, 5, 4, 6, 7, 8]
Output: 2
The windows [1, 2, 2] (indices 1 to 3) and [4, 6, 7] (indices 5 to 7) share no index, so at least two changes are needed. Raising nums[2] and nums[6] to 100 gives [3, 1, 100, 2, 5, 4, 100, 7, 8], which has no non-decreasing window.