Maximum Path Sum in Grid
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ grid.length, grid[0].length ≤ 20 - ◆
-100 ≤ grid[i][j] ≤ 100
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteStanding on any cell, the largest total reachable from there to the bottom-right corner is that cell's own value plus whichever of the two possible next moves — one step down or one step right — leads to a bigger total. Reaching the bottom-right corner costs exactly that cell's own value, since there's nowhere left to go, and stepping past the bottom or right edge simply isn't a valid move. Recursing from the top-left corner and always taking whichever next move leads to the bigger total finds the maximum path sum, though the same cell ends up recomputed every time a different path reaches it.
O(2^(m+n))O(m + n)1class Solution {
2 private int[][] grid;
3 private int m;
4 private int n;
5
6 public int maxPathSum(int[][] grid) {
7 this.grid = grid;
8 this.m = grid.length;
9 this.n = grid[0].length;
10 return solve(0, 0);
11 }
12
13 private int solve(int i, int j) {
14 if (i == m - 1 && j == n - 1) return grid[i][j];
15 int best = Integer.MIN_VALUE;
16 if (i + 1 < m) best = Math.max(best, solve(i + 1, j));
17 if (j + 1 < n) best = Math.max(best, solve(i, j + 1));
18 return grid[i][j] + best;
19 }
20}Optimal — Bottom-Up 1D DP
OptimalTrack, for the row currently being processed, the biggest total reachable from the top-left corner to each column. The very first cell just takes its own value, since nothing leads into it. Every other cell in the first row can only be reached from the left, so its total simply adds this cell's value onto the running total from the previous column. Every other cell in the first column can only be reached from above, so its total adds onto whatever is already sitting at that column. Every remaining cell picks whichever of those two arrivals — from above, or from the left — is bigger, and adds its own value on top. Sweeping through every row this way, the last column ends up holding the maximum total to the bottom-right corner.
O(m × n)O(n)1class Solution {
2 public int maxPathSum(int[][] grid) {
3 int m = grid.length, n = grid[0].length;
4 int[] dp = new int[n];
5 for (int i = 0; i < m; i++) {
6 for (int j = 0; j < n; j++) {
7 if (i == 0 && j == 0) {
8 dp[j] = grid[i][j];
9 } else if (j == 0) {
10 dp[j] = dp[j] + grid[i][j];
11 } else if (i == 0) {
12 dp[j] = dp[j - 1] + grid[i][j];
13 } else {
14 dp[j] = Math.max(dp[j], dp[j - 1]) + grid[i][j];
15 }
16 }
17 }
18 return dp[n - 1];
19 }
20}