Home > Article > Backend Development > Minimum Number of Removals to Make Mountain Array
1671. Minimum Number of Removals to Make Mountain Array
Difficulty: Hard
Topics: Array, Binary Search, Dynamic Programming, Greedy
You may recall that an array arr is a mountain array if and only if:
Given an integer array nums, return the minimum number of elements to remove to make nums a mountain array.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
We can use a dynamic programming approach with the idea of finding the maximum mountain subsequence rather than directly counting elements to remove. This approach is based on finding two Longest Increasing Subsequences (LIS) for each position in the array: one going left-to-right and the other going right-to-left. Once we have the longest possible mountain subsequence, the difference between the original array length and this subsequence length will give us the minimum elements to remove.
Identify increasing subsequence lengths:
Identify decreasing subsequence lengths:
Calculate maximum mountain length:
Get the minimum removals:
Let's implement this solution in PHP: 1671. Minimum Number of Removals to Make Mountain Array
<?php /** * @param Integer[] $nums * @return Integer */ function minimumMountainRemovals($nums) { ... ... ... /** * go to ./solution.php */ } // Example usage $nums1 = [1, 3, 1]; echo minimumMountainRemovals($nums1); // Output: 0 $nums2 = [2, 1, 1, 5, 6, 2, 3, 1]; echo minimumMountainRemovals($nums2); // Output: 3 ?>
Left LIS Calculation:
Right LIS Calculation:
Mountain Calculation:
Final Calculation:
This solution ensures that we find the maximum mountain subsequence and compute the minimum removals required to achieve a mountain array.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Minimum Number of Removals to Make Mountain Array. For more information, please follow other related articles on the PHP Chinese website!