Minimum Number of Removals to Make Mountain Array LeetCode solution in JavaScript

1
var minimumMountainRemovals = function (nums) {
2
let n = nums.length;
3
let previous = Array.from({ length: n }, (item) => 1);
4
let previous2 = Array.from({ length: n }, (item) => 1);
5
//calcultaing left and right side LIS in single iteration
6
for (let i = 0; i < n; i++) {
7
for (let j = 0; j < i; j++) {
8
//reverse indexes
9
let i2 = n - 1 - i;
10
let j2 = n - 1 - j;
11
//calculating first dp serially
12
if (nums[i] > nums[j] && previous[i] < previous[j] + 1) {
13
previous[i] = previous[j] + 1;
14
}
15
//calculating second dp reversely
16
if (nums[i2] > nums[j2] && previous2[i2] < previous2[j2] + 1) {
17
previous2[i2] = previous2[j2] + 1;
18
}
19
}
20
}
21
let max = 0;
22
for (let i = 0; i < n; i++) {
23
//golden condition// to avoid only increasing and decreasing
24
//because if a combination of 1 indicates its increasing fully or decreasing !
25
if (previous[i] > 1 && previous2[i] > 1) {
26
//at a specific index highest increasing will come from left LIS
27
// and highest decreasing will come from right side LIS
28
max = Math.max(max, previous[i] + previous2[i] - 1);
29
}
30
}
31
return n - max; //we need to remove the rest from total
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0