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.
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
// 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]));
} def min_falling_path_sum(m):
n = len(m[0])
prev = m[0][:] # best sum ending at each cell of the previous row
for r in range(1, len(m)):
prev = [m[r][c] + min(prev[max(c - 1, 0):c + 2]) for c in range(n)]
return min(prev) # the best cell of the last row
def maximum_points(p):
prev = [0, 0, 0] # prev[a] = best total so far if the last day did activity a
for day in p:
prev = [day[a] + max(prev[b] for b in range(3) if b != a) for a in range(3)]
return max(prev) // Minimum Falling Path Sum: come from the cell above, or one column to either side
int minFallingPathSum(vector<vector<int>>& m) {
int n = m[0].size();
vector<int> prev = m[0]; // best sum ending at each cell of the previous row
for (int r = 1; r < (int)m.size(); r++) {
vector<int> cur(n);
for (int c = 0; c < n; c++) {
int best = prev[c];
if (c > 0) best = min(best, prev[c - 1]);
if (c < n - 1) best = min(best, prev[c + 1]);
cur[c] = m[r][c] + best;
}
prev = cur;
}
return *min_element(prev.begin(), prev.end()); // 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(vector<vector<int>>& p) {
vector<int> prev(3, 0); // prev[a] = best total so far if the last day did activity a
for (auto& day : p) {
vector<int> cur(3, 0);
for (int a = 0; a < 3; a++)
for (int b = 0; b < 3; b++)
if (a != b) cur[a] = max(cur[a], prev[b] + day[a]);
prev = cur;
}
return *max_element(prev.begin(), prev.end());
} // Minimum Falling Path Sum: come from the cell above, or one column to either side
function minFallingPathSum(m) {
const n = m[0].length;
let prev = [...m[0]]; // best sum ending at each cell of the previous row
for (let r = 1; r < m.length; r++) {
const cur = new Array(n);
for (let c = 0; c < n; c++) {
let 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 Math.min(...prev); // the best cell of the last row
}
// Geek's Training: 3 activities a day, never the same one two days in a row
function maximumPoints(p) {
let prev = [0, 0, 0]; // prev[a] = best total so far if the last day did activity a
for (const day of p) {
const cur = [0, 0, 0];
for (let a = 0; a < 3; a++)
for (let b = 0; b < 3; b++)
if (a !== b) cur[a] = Math.max(cur[a], prev[b] + day[a]);
prev = cur;
}
return Math.max(...prev);
} The variations
-
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
rhasr + 1cells and cellccomes fromc - 1orcabove. Filling from the bottom row up leaves the answer at the top.Now you solve- Triangle Medium Stuck? ▶ video
-
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]orprev[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].
Mark it done once you can write the template from memory and you have solved the worked examples yourself.