Skip to content

Create 1671. Minimum Number of Removals to Make Mountain Array #621

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions 1671. Minimum Number of Removals to Make Mountain Array
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
class Solution {
public:
int lis(int i, vector<int>& nums, vector<int>& dp) {
if (dp[i] != -1)
return dp[i];
int maxi = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
maxi = max(maxi, lis(j, nums, dp) + 1);
}
}
return dp[i] = maxi;
}
int lds(int i, vector<int>& nums, vector<int>& dp) {
if (dp[i] != -1)
return dp[i];
int maxi = 1;
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] > nums[j]) {
maxi = max(maxi, lds(j, nums, dp) + 1);
}
}
return dp[i] = maxi;
}

int minimumMountainRemovals(vector<int>& nums) {
int n = nums.size();
if (n < 3)
return 0;
vector<int> lisOfAllIndices(n, -1);
vector<int> ldsOfAllIndices(n, -1);

for (int i = 0; i < n; i++)
lis(i, nums, lisOfAllIndices);

for (int i = n - 1; i >= 0; i--)
lds(i, nums, ldsOfAllIndices);


int maxi = 0;
for (int i = 1; i < n - 1; i++) {
if (lisOfAllIndices[i] > 1 && ldsOfAllIndices[i] > 1) {
maxi = max(maxi, lisOfAllIndices[i] + ldsOfAllIndices[i] - 1);
}
}
return n - maxi;
}
};
Loading