1671. Minimum Number of Removals to Make Mountain Array #767
-
Topics: You may recall that an array
Given an integer array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
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. Solution Outline
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) {
$n = count($nums);
// Step 1: Calculate leftLIS (Longest Increasing Subsequence from left to right)
$leftLIS = array_fill(0, $n, 1);
for ($i = 1; $i < $n; $i++) {
for ($j = 0; $j < $i; $j++) {
if ($nums[$j] < $nums[$i]) {
$leftLIS[$i] = max($leftLIS[$i], $leftLIS[$j] + 1);
}
}
}
// Step 2: Calculate rightLIS (Longest Increasing Subsequence from right to left)
$rightLIS = array_fill(0, $n, 1);
for ($i = $n - 2; $i >= 0; $i--) {
for ($j = $n - 1; $j > $i; $j--) {
if ($nums[$j] < $nums[$i]) {
$rightLIS[$i] = max($rightLIS[$i], $rightLIS[$j] + 1);
}
}
}
// Step 3: Find the maximum length of a mountain sequence
$maxMountainLength = 0;
for ($i = 1; $i < $n - 1; $i++) {
if ($leftLIS[$i] > 1 && $rightLIS[$i] > 1) { // Valid peak
$maxMountainLength = max($maxMountainLength, $leftLIS[$i] + $rightLIS[$i] - 1);
}
}
// Step 4: Calculate minimum removals
return $n - $maxMountainLength;
}
// 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
?> Explanation:
Complexity Analysis
This solution ensures that we find the maximum mountain subsequence and compute the minimum removals required to achieve a mountain array. |
Beta Was this translation helpful? Give feedback.
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.
Solution Outline
Identify increasing subsequence lengths:
leftLIS
array, whereleftLIS[i]
represents the length of the longest increasing subsequence ending ati
(going left to right).I…