-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMinimumPathSum.java
More file actions
27 lines (22 loc) · 808 Bytes
/
MinimumPathSum.java
File metadata and controls
27 lines (22 loc) · 808 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// https://leetcode.com/problems/minimum-path-sum
// T: O(m * n)
// S: O(1)
public class MinimumPathSum {
public int minPathSum(int[][] grid) {
final int rows = grid.length, columns = grid[0].length;
// last row
for (int column = columns - 2 ; column >= 0 ; column--) {
grid[rows - 1][column] += grid[rows - 1][column + 1];
}
// last column
for (int row = rows - 2 ; row >= 0 ; row--) {
grid[row][columns - 1] += grid[row + 1][columns - 1];
}
for (int row = rows - 2 ; row >= 0 ; row--) {
for (int column = columns - 2 ; column >= 0 ; column--) {
grid[row][column] += Math.min(grid[row + 1][column], grid[row][column + 1]);
}
}
return grid[0][0];
}
}