Make Array Non-decreasing - Problem

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.

A subarray is a contiguous sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,4,2,1]
Output: 1
💡 Note: We can replace the entire array [3,4,2,1] with its maximum value 4, resulting in [4] which is non-decreasing and has length 1.
Example 2 — Already Non-decreasing
$ Input: nums = [1,2,3,4]
Output: 4
💡 Note: The array is already non-decreasing, so no operations are needed. The maximum length is 4.
Example 3 — Partial Replacement
$ Input: nums = [1,3,2,4]
Output: 3
💡 Note: Replace subarray [3,2] with 3, resulting in [1,3,4] which is non-decreasing with length 3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Make Array Non-decreasing Greedy with Monotonic Stack Approach INPUT nums = [3, 4, 2, 1] 3 idx 0 4 idx 1 2 idx 2 1 idx 3 Goal: Make array non-decreasing by replacing subarrays with their maximum value. Violations detected: 4 greater than 2 (idx 1,2) 2 greater than 1 (idx 2,3) ALGORITHM STEPS 1 Initialize Stack Use monotonic stack to track non-decreasing seq 2 Process Elements For each num, pop stack while top greater than num 3 Merge Subarrays Popped elements merge into max value 4 Count Result Stack size = max array size after operations Stack Trace: [3] --> [3,4] --> [3,2] --> [1] (final: size 1) 4 merges with 2, then 1 FINAL RESULT After merging all elements: 3 4 2 1 4 max value Output: 1 OK - Array is now non-decreasing [4] Key Insight: A monotonic stack tracks elements that can remain in the non-decreasing array. When we encounter a smaller element, previous larger elements must merge with it (replaced by max). The stack size gives the maximum possible array length. For [3,4,2,1]: only the final merged element (4) survives, so answer is 1. TutorialsPoint - Make Array Non-decreasing | Greedy with Monotonic Stack Approach
Asked in
Google 35 Amazon 28 Microsoft 22 Apple 18
32.4K Views
Medium Frequency
~25 min Avg. Time
890 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