To solve the problem of converting an array nums into a mountain array with the minimum number of deletions, we need to identify the longest mountain subsequence within the array and then compute the number of deletions required to achieve it.
Here are the steps:
Use dynamic programming to find the length of the longest increasing subsequence (LIS) up to each index i.
Use dynamic programming to find the length of the longest decreasing subsequence (LDS) from each index i.
Combine results from steps 1 and 2 to find a peak i such that both the increasing sequence up to i and the decreasing sequence starting from i are maximized.
The number of deletions required will be the total length of the array minus the length of the longest mountain subsequence.
classSolution {
publicintminimumMountainRemovals(int[] nums) {
int n = nums.length;
int[] lis =newint[n];
int[] lds =newint[n];
// Find LIS for each elementfor (int i = 0; i < n; i++) {
lis[i]= 1;
for (int j = 0; j < i; j++) {
if (nums[i]> nums[j]) {
lis[i]= Math.max(lis[i], lis[j]+ 1);
}
}
}
// Find LDS for each elementfor (int i = n - 1; i >= 0; i--) {
lds[i]= 1;
for (int j = n - 1; j > i; j--) {
if (nums[i]> nums[j]) {
lds[i]= Math.max(lds[i], lds[j]+ 1);
}
}
}
// Find the maximum length of mountain arrayint ans = Integer.MAX_VALUE;
for (int i = 1; i < n - 1; i++) {
if (lis[i]> 1 && lds[i]> 1) { // Peak must be valid ans = Math.min(ans, n - (lis[i]+ lds[i]- 1));
}
}
return ans;
}
}
classSolution:
defminimumMountainRemovals(self, nums: List[int]) -> int:
n = len(nums)
lis: List[int] = [1] * n
lds: List[int] = [1] * n
# Find LIS for each elementfor i in range(n):
for j in range(i):
if nums[i] > nums[j]:
lis[i] = max(lis[i], lis[j] +1)
# Find LDS for each elementfor i in range(n-1, -1, -1):
for j in range(n-1, i, -1):
if nums[i] > nums[j]:
lds[i] = max(lds[i], lds[j] +1)
# Find the maximum length of mountain array ans: int = float('inf')
for i in range(1, n-1):
if lis[i] >1and lds[i] >1: # Peak must be valid ans = min(ans, n - (lis[i] + lds[i] -1))
return ans