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: Transform [3,4,2,1]3421Input Array (not non-decreasing)Replace with max(3,4,2,1) = 44Output: Non-decreasing arrayMaximum Length: 1
Understanding the Visualization
1
Input
Array with decreasing elements [3,4,2,1]
2
Replace
Replace entire array with maximum value 4
3
Output
Non-decreasing array [4] with length 1
Key Takeaway
🎯 Key Insight: Use a monotonic stack to greedily maintain the longest possible non-decreasing sequence
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