Skip to lesson

1D Dynamic Programming Practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Synthesizing 1D dynamic programming patterns strengthens intuition for state definitions and transitions. You combine lookback windows, state dualities, and counting principles to solve diverse algorithmic problems.

Pattern Recognition in 1D DP

Identifying subproblem structure determines whether a problem requires dynamic programming. Linear sequences often exhibit optimal substructure with transitions depending on preceding indices.

Ask whether current choices depend on past decisions or future states. Look for overlapping subproblems where identical states are evaluated multiple times.

A clear recurrence relation forms the foundation for every working dynamic programming solution.

Multi-State Tracking and Dualities

Some problems require maintaining complementary state variables simultaneously. For example, multiplying two negative numbers creates a positive product.

Maximum product subarray tracks both minimum and maximum values at each position. When encountering negative numbers, the minimum and maximum swap roles.

Step by step

Step 1 of 4

Array: 2, 3, -2, 4.
cur
2
maxP
2
minP
2
ans
2
At index 0, current value 2 initializes both max and min product tracking.

Example 1 · Maximum Product Subarray

MaxProductSubarray.javaJava
public class MaxProductSubarray {    public static int maxProduct(int[] nums) {        if (nums == null || nums.length == 0) return 0;        int maxP = nums[0];        int minP = nums[0];        int ans = nums[0];        for (int i = 1; i < nums.length; i++) {            int x = nums[i];            if (x < 0) {                int temp = maxP;                maxP = minP;                minP = temp;            }            maxP = Math.max(x, maxP * x);            minP = Math.min(x, minP * x);            ans = Math.max(ans, maxP);        }        return ans;    }
    public static void main(String[] args) {        int[] a1 = {2, 3, -2, 4};        System.out.println("Max product for {2, 3, -2, 4}: " + maxProduct(a1));        int[] a2 = {-2, 0, -1};        System.out.println("Max product for {-2, 0, -1}: " + maxProduct(a2));    }}
Output
Max product for {2, 3, -2, 4}: 6
Max product for {-2, 0, -1}: 0

What this code does

  • Tracking both maximum and minimum products handles sign reversals from negative numbers.
  • When x is negative, multiplying flips the maximum and minimum values.
  • The method processes the array in O(n) time using O(1) auxiliary variables.

Dual state tracking prevents missing non-linear transitions caused by negative factors.

Lookback Windows and Space Compaction

When state transitions depend on a bounded history of k steps, rolling arrays suffice. A circular buffer of size k reduces memory overhead.

For unbounded lookback, monotonic data structures or binary search can accelerate transitions. These tools reduce inner search loops from linear to logarithmic time.

Always analyze lookback depth before finalizing memory allocations in production systems.

Counting Combinations and Optimal Paths

Dynamic programming solves counting problems in addition to optimization queries. Instead of selecting the minimum or maximum, transitions sum ways from valid predecessors.

Tracking both optimal value and combination count simultaneously resolves multi-objective problems. This pattern computes the number of longest increasing subsequences.

Example 2 · Perfect Squares Minimum Count

PerfectSquares.javaJava
import java.util.Arrays;
public class PerfectSquares {    public static int numSquares(int n) {        int[] dp = new int[n + 1];        Arrays.fill(dp, Integer.MAX_VALUE);        dp[0] = 0;        for (int i = 1; i <= n; i++) {            for (int j = 1; j * j <= i; j++) {                dp[i] = Math.min(dp[i], dp[i - j * j] + 1);            }        }        return dp[n];    }
    public static void main(String[] args) {        System.out.println("Squares summing to 12: " + numSquares(12));        System.out.println("Squares summing to 13: " + numSquares(13));    }}
Output
Squares summing to 12: 3
Squares summing to 13: 2

What this code does

  • State dp[i] represents the minimum count of perfect squares summing to i.
  • For each number i, the inner loop explores candidate squares j * j.
  • Values 12 and 13 decompose into optimal combinations of 3 and 2 squares.

Example 3 · Number of Longest Increasing Subsequences

NumberOfLIS.javaJava
import java.util.Arrays;
public class NumberOfLIS {    public static int findNumberOfLIS(int[] nums) {        if (nums == null || nums.length == 0) return 0;        int n = nums.length;        int[] lengths = new int[n];        int[] counts = new int[n];        Arrays.fill(lengths, 1);        Arrays.fill(counts, 1);        int maxLen = 1;        for (int i = 0; i < n; i++) {            for (int j = 0; j < i; j++) {                if (nums[j] < nums[i]) {                    if (lengths[j] + 1 > lengths[i]) {                        lengths[i] = lengths[j] + 1;                        counts[i] = counts[j];                    } else if (lengths[j] + 1 == lengths[i]) {                        counts[i] += counts[j];                    }                }            }            if (lengths[i] > maxLen) {                maxLen = lengths[i];            }        }        int totalWays = 0;        for (int i = 0; i < n; i++) {            if (lengths[i] == maxLen) {                totalWays += counts[i];            }        }        return totalWays;    }
    public static void main(String[] args) {        int[] nums1 = {1, 3, 5, 4, 7};        System.out.println("Number of LIS for set 1: " + findNumberOfLIS(nums1));        int[] nums2 = {2, 2, 2, 2, 2};        System.out.println("Number of LIS for set 2: " + findNumberOfLIS(nums2));    }}
Output
Number of LIS for set 1: 2
Number of LIS for set 2: 5

What this code does

  • Arrays lengths and counts track maximum subsequence length and path combinations.
  • When a strictly longer subsequence appears, the count resets to the predecessor count.
  • When an equal length path occurs, the count accumulates from the predecessor.

Summing valid predecessor counts yields total paths without exponential combinatorial search.

Finish up

Mark complete & continue

Next: Grid paths