Minimum Number of Removals to Make Mountain Array - Problem

You may recall that an array arr is a mountain array if and only if:

  • arr.length >= 3
  • There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array.

Input & Output

Example 1 — Basic Mountain
$ Input: nums = [1,3,1]
Output: 0
💡 Note: The array [1,3,1] is already a mountain array with peak at index 1: 1 < 3 > 1. No removals needed.
Example 2 — Need Removals
$ Input: nums = [2,1,1,5,6,2,3,1]
Output: 3
💡 Note: We can form mountain [2,5,6,3,1] by removing elements at indices 1, 2, and 7. This gives us 8 - 5 = 3 removals.
Example 3 — Small Array
$ Input: nums = [4,3,2,1,1,2,3,1]
Output: 4
💡 Note: We can form mountain [1,2,3,1] from the latter part. This requires removing 4 elements.

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Mountain Array Formation: Minimum Removals21156231Input: [2,1,1,5,6,2,3,1]RemoveRemoveRemoveKeepKeepRemoveKeepKeepResulting Mountain: [5,6,3,1]Length = 4, Removals = 8 - 4 = 4... Wait, should be 3!Actually: [2,5,6,3,1] gives 5 elements, so 3 removals
Understanding the Visualization
1
Input Array
Given array that needs to become a mountain
2
Find Peak
Identify optimal peak position and calculate mountain length
3
Remove Elements
Remove minimum elements to form valid mountain
Key Takeaway
🎯 Key Insight: Find the longest mountain subsequence using LIS+LDS, then remove the remaining elements
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.5K Views
Medium Frequency
~35 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