|
| 1 | +/** |
| 2 | + * 1671. Minimum Number of Removals to Make Mountain Array |
| 3 | + * https://leetcode.com/problems/minimum-number-of-removals-to-make-mountain-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You may recall that an array arr is a mountain array if and only if: |
| 7 | + * - arr.length >= 3 |
| 8 | + * - There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: |
| 9 | + * - arr[0] < arr[1] < ... < arr[i - 1] < arr[i] |
| 10 | + * - arr[i] > arr[i + 1] > ... > arr[arr.length - 1] |
| 11 | + * |
| 12 | + * Given an integer array nums, return the minimum number of elements to remove to make |
| 13 | + * nums a mountain array. |
| 14 | + */ |
| 15 | + |
| 16 | +/** |
| 17 | + * @param {number[]} nums |
| 18 | + * @return {number} |
| 19 | + */ |
| 20 | +var minimumMountainRemovals = function(nums) { |
| 21 | + const length = nums.length; |
| 22 | + const leftLIS = new Array(length).fill(1); |
| 23 | + const rightLIS = new Array(length).fill(1); |
| 24 | + |
| 25 | + for (let i = 1; i < length; i++) { |
| 26 | + for (let j = 0; j < i; j++) { |
| 27 | + if (nums[i] > nums[j]) { |
| 28 | + leftLIS[i] = Math.max(leftLIS[i], leftLIS[j] + 1); |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + for (let i = length - 2; i >= 0; i--) { |
| 34 | + for (let j = length - 1; j > i; j--) { |
| 35 | + if (nums[i] > nums[j]) { |
| 36 | + rightLIS[i] = Math.max(rightLIS[i], rightLIS[j] + 1); |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + let maxMountainLength = 0; |
| 42 | + for (let i = 1; i < length - 1; i++) { |
| 43 | + if (leftLIS[i] > 1 && rightLIS[i] > 1) { |
| 44 | + maxMountainLength = Math.max(maxMountainLength, leftLIS[i] + rightLIS[i] - 1); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + return length - maxMountainLength; |
| 49 | +}; |
0 commit comments