Dynamic Programming · Pattern 4 of 12

Row by row: the best of the last row

Fill the table one row at a time; each cell takes the best of a few cells in the row above. There is no single end cell, so the answer is the max or min over the whole last row.

2 variations · 3 problems · 3 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Move down one row per step, to a nearby column
  • Start anywhere in the first row, end anywhere in the last row
  • You may not repeat the same choice on two consecutive rows or days

The template

2D DP - max/min of last row
// Minimum Falling Path Sum: from (r, c) you can come from (r - 1, c - 1), (r - 1, c), (r - 1, c + 1)
int minFallingPathSum(int[][] m) {
    int n = m[0].length;
    int[] prev = m[0].clone();             // best sum ending at each cell of the previous row
    for (int r = 1; r < m.length; r++) {
        int[] cur = new int[n];
        for (int c = 0; c < n; c++) {
            int best = prev[c];
            if (c > 0) best = Math.min(best, prev[c - 1]);
            if (c < n - 1) best = Math.min(best, prev[c + 1]);
            cur[c] = m[r][c] + best;
        }
        prev = cur;
    }
    return Arrays.stream(prev).min().getAsInt();   // the best cell of the last row
}

// Geek's Training: 3 activities a day, never the same one two days in a row
int maximumPoints(int[][] p) {
    int[] prev = new int[3];               // prev[a] = best total so far if the last day did activity a
    for (int[] day : p) {
        int[] cur = new int[3];
        for (int a = 0; a < 3; a++)
            for (int b = 0; b < 3; b++)
                if (a != b) cur[a] = Math.max(cur[a], prev[b] + day[a]);
        prev = cur;
    }
    return Math.max(prev[0], Math.max(prev[1], prev[2]));
}

The variations

  1. 1Nearby cells in the row above

    Each cell adds its value to the best of the two or three cells above it. In Triangle, row r has r + 1 cells and cell c comes from c - 1 or c above. Filling from the bottom row up leaves the answer at the top.

    Now you solve
  2. 2Not the same choice twice in a row

    The column is now the last choice made (the activity of the previous day). Each new day may take any activity except that one, so cur[a] = day[a] + max(prev[b] for b != a).

Mistakes to avoid

  • Returning the value of one fixed cell when the path may end anywhere in the last row.
  • Reading prev[c - 1] or prev[c + 1] outside the row at the edges.
  • Triangle top-down needs the min over the last row; filling bottom-up instead leaves the answer at the top, dp[0].
Next: Squares: the largest square ending at each cell →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.