↓Skip to main content

Dynamic-Programming

String DP
·2 mins
Algorithm Dynamic-Programming String Lcs Palindrome
Prefix tables, edit operations, subsequences, and interval palindrome DP
Knapsack DP
·3 mins
Algorithm Dynamic-Programming Knapsack Subset-Sum
0/1, unbounded, reachability, counting, and optimization states
Grid DP
·3 mins
Algorithm Dynamic-Programming Grid-Dp
Counting, cost optimization, reverse resource DP, and local geometry
LeetCode 940: Distinct Subsequences II
·2 mins
LeetCode Hard Dynamic-Programming String
LeetCode 940 note: group by last character; distinct subsequences ending with c = every current distinct subsequence with c appended, plus c itself, replacing the old value
LeetCode 2973: Find Number of Coins to Place in Tree Nodes
·3 mins
LeetCode Hard Dynamic-Programming Tree-Dp Depth-First-Search Sorting Heap Tree
LeetCode 2973 note: the max product of three is either the three largest or the two smallest times the largest, so each subtree returns only its 2 smallest and 3 largest values, merged in post-order
LeetCode 1246: Palindrome Removal
·2 mins
LeetCode Hard Dynamic-Programming Interval-Dp Array
LeetCode 1246 note: interval DP taking the minimum of removing arr[i] alone, removing equal ends together with the inside, or splitting into two parts
LeetCode 1425: Constrained Subsequence Sum
·2 mins
LeetCode Hard Sliding-Window Dynamic-Programming Monotonic-Queue Heap Queue Array
LeetCode 1425 note: dp[i] = nums[i] + max(0, max of the previous k dp values); that max is a sliding window maximum, available in O(1) from a monotonic deque
LeetCode 1373: Maximum Sum BST in Binary Tree
·2 mins
LeetCode Hard Dynamic-Programming Tree-Dp Binary-Search-Tree Depth-First-Search Tree
LeetCode 1373 note: a post-order traversal returns (sum, min, max, is_bst); a node roots a BST when the left max < its value < the right min
LeetCode 996: Number of Squareful Arrays
·3 mins
LeetCode Hard Dynamic-Programming Bitmask Backtracking Math Hash-Table
LeetCode 996 note: with n at most 12, use bitmask DP: dp[mask][last] = permutations using the set mask and ending with last; dedupe by using equal values in index order
LeetCode 773: Sliding Puzzle
·2 mins
LeetCode Hard Breadth-First-Search Dynamic-Programming Memoization Matrix
LeetCode 773 note: there are only 6! = 720 boards, so flatten each board into a string as a BFS state, with swaps of 0 and a neighbor as the moves
LeetCode 2376: Count Special Integers
·2 mins
LeetCode Hard Dynamic-Programming Digit-Dp Math Bitmask
LeetCode 2376 note: digit DP with state (pos, tight, started, mask); the mask records used digits, and leading zeros must not mark 0 as used
LeetCode 2163: Minimum Difference in Sums After Removal of Elements
·2 mins
LeetCode Hard Dynamic-Programming Heap Array
LeetCode 2163 note: try every boundary k between the two parts; the left takes the n smallest of nums[:k] (a max-heap) and the right the n largest of nums[k:] (a min-heap), one prefix and one suffix pass