Session 43: DP 5
Original Session
Date: 16 Feb 2025
Topic: DP
Concept:
Programs
- 1526. Minimum Number of Increments on Subarrays to Form a Target Array.
- leetcode here
public int minNumberOperations(int[] target) { int ans = target[0]; for (int i=1; i<target.length; i++) { if (target[i] > target[i-1]) { ans += target[i] - target[i-1]; } } return ans; }
- leetcode here
- 1653. Minimum Deletions to Make String Balanced.
- leetcode here
public int minimumDeletions(String s) { int n = s.length(); int aCount = 0; for (int i=0; i<n; i++) { if (s.charAt(i) == 'a') { aCount ++; } } int bCount = 0, ans = aCount; for (int i=0; i<n; i++) { if (s.charAt(i) == 'a') { aCount --; } ans = Math.min(ans, aCount + bCount); if (s.charAt(i) == 'b') { bCount ++; } } return ans; }
- leetcode here
- 1987. Number of Unique Good Subsequences
- leetcode here
public int numberOfUniqueGoodSubsequences(String binary) { int mod = 1000000007; int endWithOne = 0; int endWithZero = 0; int hasZero = 0; for (int i=0; i<binary.length(); i++) { if (binary.charAt(i) == '1') { endWithOne = (endWithOne + endWithZero + 1) % mod; } else { hasZero = 1; endWithZero = (endWithOne + endWithZero) % mod; } } return (endWithOne + endWithZero + hasZero) % mod; }
- leetcode here
- 87. Scramble String
- leetcode here
public boolean isScramble(String s1, String s2) { if (s1.equals(s2)) return true; if (s1.length() != s2.length()) return false; String key = s1 + "#" + s2; if (dp.containsKey(key)) return dp.get(key); int n = s1.length(); // Check if both strings have the same character counts (anagram check) int[] freq = new int[26]; for (int i = 0; i < n; i++) { freq[s1.charAt(i) - 'a']++; freq[s2.charAt(i) - 'a']--; } for (int count : freq) { if (count != 0) { dp.put(key, false); return false; } } for (int i = 1; i < n; i++) { // Case 1: No Swap if (isScramble(s1.substring(0, i), s2.substring(0, i)) && isScramble(s1.substring(i), s2.substring(i))) { dp.put(key, true); return true; } // Case 2: Swap if (isScramble(s1.substring(0, i), s2.substring(n - i)) && isScramble(s1.substring(i), s2.substring(0, n - i))) { dp.put(key, true); return true; } } dp.put(key, false); return false; } }
- leetcode here
- Programs
- Programs
- Programs
- Programs
- Programs
- Programs
- Programs