From d0698af797e43b2e22c49a574f3037ff6f92a0e2 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Wed, 30 Oct 2024 22:54:53 +0530 Subject: [PATCH] Create 1671. Minimum Number of Removals to Make Mountain Array --- ... Number of Removals to Make Mountain Array | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 1671. Minimum Number of Removals to Make Mountain Array diff --git a/1671. Minimum Number of Removals to Make Mountain Array b/1671. Minimum Number of Removals to Make Mountain Array new file mode 100644 index 0000000..d31f694 --- /dev/null +++ b/1671. Minimum Number of Removals to Make Mountain Array @@ -0,0 +1,48 @@ +class Solution { +public: + int lis(int i, vector& nums, vector& 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& nums, vector& 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& nums) { + int n = nums.size(); + if (n < 3) + return 0; + vector lisOfAllIndices(n, -1); + vector 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; + } +};