Make Array Non-decreasing Problem
Description
LeetCode Problem 3523.
You are given an integer array nums. In one operation, you can select a subarray and replace it with a single element equal to its maximum value.
Return the maximum possible size of the array after performing zero or more operations such that the resulting array is non-decreasing.
Example 1:
Input: nums = [4,2,5,3,5]
Output: 3
Explanation:
One way to achieve the maximum size is:
1. Replace subarray nums[1..2] = [2, 5] with 5 → [4, 5, 3, 5].
2. Replace subarray nums[2..3] = [3, 5] with 5 → [4, 5, 5].
The final array [4, 5, 5] is non-decreasing with size 3.
Example 2:
Input: nums = [1,2,3]
Output: 3
Explanation:
No operation is needed as the array [1,2,3] is already non-decreasing.
Constraints:
1 <= nums.length <= 2 * 10^51 <= nums[i] <= 2 * 10^5
Solution
Approach: Count Prefix Maximums
Replacing a subarray by its maximum can only remove elements that are smaller than something to their left or right inside the chosen subarray. An element that is smaller than a previous element must be merged into a block with a larger element, so it disappears; an element that is at least as large as everything before it can stay.
So scan from left to right with the running maximum mx and count every element x >= mx, updating mx = x. The count is the maximum possible length of a non-decreasing array.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maximumPossibleSize(self, nums: List[int]) -> int:
ans = mx = 0
for x in nums:
if mx <= x:
ans += 1
mx = x
return ans