Skip to content

Commit 38eedb1

Browse files
authored
Create 1671. Minimum Number of Removals to Make Mountain Array (#621)
2 parents 72b5b8e + d0698af commit 38eedb1

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Solution {
2+
public:
3+
int lis(int i, vector<int>& nums, vector<int>& dp) {
4+
if (dp[i] != -1)
5+
return dp[i];
6+
int maxi = 1;
7+
for (int j = 0; j < i; j++) {
8+
if (nums[i] > nums[j]) {
9+
maxi = max(maxi, lis(j, nums, dp) + 1);
10+
}
11+
}
12+
return dp[i] = maxi;
13+
}
14+
int lds(int i, vector<int>& nums, vector<int>& dp) {
15+
if (dp[i] != -1)
16+
return dp[i];
17+
int maxi = 1;
18+
for (int j = i + 1; j < nums.size(); j++) {
19+
if (nums[i] > nums[j]) {
20+
maxi = max(maxi, lds(j, nums, dp) + 1);
21+
}
22+
}
23+
return dp[i] = maxi;
24+
}
25+
26+
int minimumMountainRemovals(vector<int>& nums) {
27+
int n = nums.size();
28+
if (n < 3)
29+
return 0;
30+
vector<int> lisOfAllIndices(n, -1);
31+
vector<int> ldsOfAllIndices(n, -1);
32+
33+
for (int i = 0; i < n; i++)
34+
lis(i, nums, lisOfAllIndices);
35+
36+
for (int i = n - 1; i >= 0; i--)
37+
lds(i, nums, ldsOfAllIndices);
38+
39+
40+
int maxi = 0;
41+
for (int i = 1; i < n - 1; i++) {
42+
if (lisOfAllIndices[i] > 1 && ldsOfAllIndices[i] > 1) {
43+
maxi = max(maxi, lisOfAllIndices[i] + ldsOfAllIndices[i] - 1);
44+
}
45+
}
46+
return n - maxi;
47+
}
48+
};

0 commit comments

Comments
 (0)