Make Array Non-decreasing - Problem

Imagine you have an integer array that's currently out of order. You have a special power: you can select any subarray (a contiguous portion) and replace it with a single element equal to the maximum value in that subarray!

Your mission is to use this operation strategically to create the longest possible non-decreasing array. You can perform this operation zero or more times.

Goal: Return the maximum possible size of the array after performing operations such that the resulting array is non-decreasing (each element โ‰ค next element).

Example: [3, 1, 5, 2, 4] โ†’ You could replace [1, 5, 2] with 5 to get [3, 5, 4], then replace [5, 4] with 5 to get [3, 5].

Input & Output

example_1.py โ€” Basic Replacement
$ Input: [3, 1, 5, 2, 4]
โ€บ Output: 3
๐Ÿ’ก Note: Replace [1,5,2] with max value 5 to get [3,5,4]. Then replace [5,4] with 5 to get [3,5]. Final non-decreasing array has length 3.
example_2.py โ€” Already Non-decreasing
$ Input: [1, 2, 3, 4, 5]
โ€บ Output: 5
๐Ÿ’ก Note: Array is already non-decreasing, so no operations needed. Maximum length is 5.
example_3.py โ€” Single Element
$ Input: [5]
โ€บ Output: 1
๐Ÿ’ก Note: Single element array is always non-decreasing. Maximum length is 1.

Visualization

Tap to expand
Array to Mountain Range TransformationStep 1: Original Array as Mountains31524Step 2: Identify Problem AreasViolates non-decreasing: 3โ†’1โ†’5โ†’2Step 3: Strategic Replacement35max([1,5,2]) = 54Final Result353 โ‰ค 5 โœ“Maximum Length: 2The key is finding the optimal combination of replacements to maximize the final array length
Understanding the Visualization
1
Original Mountains
Start with the original array as mountain peaks
2
Identify Valleys
Find sections that violate non-decreasing property
3
Strategic Flattening
Replace problematic sections with their maximum values
4
Optimal Path
Achieve the longest possible non-decreasing sequence
Key Takeaway
๐ŸŽฏ Key Insight: We can use dynamic programming to explore all possible replacement strategies and find the one that yields the longest non-decreasing sequence.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(nยฒ * 2^n)

Memoization helps but still explores exponential states in worst case

n
2n
โš  Quadratic Growth
Space Complexity
O(nยฒ * max_value)

Memoization table plus recursion stack

n
2n
โš  Quadratic Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 103
  • 1 โ‰ค nums[i] โ‰ค 106
  • The array contains only positive integers
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
23.8K Views
Medium Frequency
~25 min Avg. Time
892 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