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.
Example 1:
Input: nums = [1,3,1]
Output: 0
Explanation: The array itself is a mountain array so we do not need to remove any elements.
Example 2:
Input: nums = [2,1,1,5,6,2,3,1]
Output: 3
Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1].
Constraints:
- 3 <= nums.length <= 1000
- 1 <= nums[i] <= 109
- It is guaranteed that you can make a mountain array out of nums.
假设 left(i)为从 nums[0]开始到 nums[i]的最长的单调递增数组的长度, 那 left(i) = max(left(j) + 1, left(k) + 1 … left(l) + 1), 其中 j, k, l 均小于 i, 且 nums[j], nums[k], nums[l]均小于 nums[i]。right(i)为从 nums[i]开始到 nums[nums.len()-1]的最长的单调递减数组的长度, 与 left(i)类似, 只不过方向反过来了。有了这两个, 我们可以轻松的计算出以 i 为"山顶", 左右两侧所需要移除的元素数量。
use std::cmp::Reverse;
use std::collections::BinaryHeap;
impl Solution {
pub fn minimum_mountain_removals(nums: Vec<i32>) -> i32 {
let mut left: Vec<i32> = vec![0; nums.len()];
let mut left_heap = BinaryHeap::new();
left_heap.push(Reverse((nums[0], 0)));
for i in 1..nums.len() {
let mut l = Vec::new();
while let Some(Reverse((n, c))) = left_heap.pop() {
l.push((n, c));
if n >= nums[i] {
break;
}
left[i] = left[i].max(c + 1);
}
for p in l {
left_heap.push(Reverse(p));
}
left_heap.push(Reverse((nums[i], left[i])));
}
let mut right: Vec<i32> = vec![0; nums.len()];
let mut right_heap = BinaryHeap::new();
right_heap.push(Reverse((*nums.last().unwrap(), 0)));
for i in (0..nums.len() - 1).rev() {
let mut l = Vec::new();
while let Some(Reverse((n, c))) = right_heap.pop() {
l.push((n, c));
if n >= nums[i] {
break;
}
right[i] = right[i].max(c + 1);
}
for p in l {
right_heap.push(Reverse(p));
}
right_heap.push(Reverse((nums[i], right[i])));
}
let mut ans = i32::MAX;
for i in 0..nums.len() {
if left[i] > 0 && right[i] > 0 {
ans = ans.min(nums.len() as i32 - left[i] - right[i] - 1)
}
}
ans
}
}

1280

被折叠的 条评论
为什么被折叠?



