- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 52 lines of Java from the credited upstream file 1671.java.
- The implementation visibly relies on sequence storage, ordered lookup, cached states.
- 3 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int minimumMountainRemovals(int[] nums) {3 int[] l = lengthOfLIS(nums);4 int[] r = reversed(lengthOfLIS(reversed(nums)));5 int maxMountainSeq = 0;6 7 for (int i = 0; i < nums.length; ++i)8 if (l[i] > 1 && r[i] > 1)9 maxMountainSeq = Math.max(maxMountainSeq, l[i] + r[i] - 1);10 11 return nums.length - maxMountainSeq;12 }13 14 15 private int[] lengthOfLIS(int[] nums) {16 17 18 List<Integer> tails = new ArrayList<>();19 20 int[] dp = new int[nums.length];21 for (int i = 0; i < nums.length; ++i) {22 final int num = nums[i];23 if (tails.isEmpty() || num > tails.get(tails.size() - 1))24 tails.add(num);25 else26 tails.set(firstGreaterEqual(tails, num), num);27 dp[i] = tails.size();28 }29 return dp;30 }31 32 private int firstGreaterEqual(List<Integer> arr, int target) {33 final int i = Collections.binarySearch(arr, target);34 return i < 0 ? -i - 1 : i;35 }36 37 private int[] reversed(int[] nums) {38 int[] arr = nums.clone();39 int l = 0;40 int r = nums.length - 1;41 while (l < r)42 swap(arr, l++, r--);43 return arr;44 }45 46 private void swap(int[] arr, int i, int j) {47 final int temp = arr[i];48 arr[i] = arr[j];49 arr[j] = temp;50 }51}52