1212(m)
1313Find the path where its sum is the smallest.
1414
15- All numbers given are positive.
1615The Time Complexity of your algorithm should be smaller than or equal to O(mn).
17- The Space Complexity of your algorithm should be smaller than or equal to O(mn ).
16+ The Space Complexity of your algorithm should be smaller than or equal to O(n ).
1817You can only move from the top left corner to the down right corner.
1918You can only move one step down or right.
2019
@@ -25,46 +24,41 @@ The Space Complexity of your algorithm should be smaller than or equal to O(mn).
2524
2625For more information see https://www.geeksforgeeks.org/maximum-path-sum-matrix/
2726 */
28- public class MinimumPathSum {
27+ public final class MinimumPathSum {
2928
30- public void testRegular () {
31- int [][] grid = {{1 , 3 , 1 }, {1 , 5 , 1 }, {4 , 2 , 1 }};
32- System .out .println (minimumPathSum (grid ));
29+ private MinimumPathSum () {
3330 }
3431
35- public void testLessColumns () {
36- int [][] grid = {{1 , 2 }, {5 , 6 }, {1 , 1 }};
37- System .out .println (minimumPathSum (grid ));
38- }
39-
40- public void testLessRows () {
41- int [][] grid = {{2 , 3 , 3 }, {7 , 2 , 1 }};
42- System .out .println (minimumPathSum (grid ));
43- }
32+ public static int minimumPathSum (final int [][] grid ) {
33+ int numRows = grid .length ;
34+ int numCols = grid [0 ].length ;
4435
45- public void testOneRowOneColumn () {
46- int [][] grid = {{2 }};
47- System .out .println (minimumPathSum (grid ));
48- }
49-
50- public static int minimumPathSum (int [][] grid ) {
51- int m = grid .length , n = grid [0 ].length ;
52- if (n == 0 ) {
36+ if (numCols == 0 ) {
5337 return 0 ;
5438 }
55- int [][] dp = new int [m ][n ];
56- dp [0 ][0 ] = grid [0 ][0 ];
57- for (int i = 0 ; i < n - 1 ; i ++) {
58- dp [0 ][i + 1 ] = dp [0 ][i ] + grid [0 ][i + 1 ];
59- }
60- for (int i = 0 ; i < m - 1 ; i ++) {
61- dp [i + 1 ][0 ] = dp [i ][0 ] + grid [i + 1 ][0 ];
39+
40+ int [] dp = new int [numCols ];
41+
42+ // Initialize the first element of the dp array
43+ dp [0 ] = grid [0 ][0 ];
44+
45+ // Calculate the minimum path sums for the first row
46+ for (int col = 1 ; col < numCols ; col ++) {
47+ dp [col ] = dp [col - 1 ] + grid [0 ][col ];
6248 }
63- for (int i = 1 ; i < m ; i ++) {
64- for (int j = 1 ; j < n ; j ++) {
65- dp [i ][j ] = Math .min (dp [i - 1 ][j ], dp [i ][j - 1 ]) + grid [i ][j ];
49+
50+ // Calculate the minimum path sums for the remaining rows
51+ for (int row = 1 ; row < numRows ; row ++) {
52+ // Update the minimum path sum for the first column
53+ dp [0 ] += grid [row ][0 ];
54+
55+ for (int col = 1 ; col < numCols ; col ++) {
56+ // Choose the minimum path sum from the left or above
57+ dp [col ] = Math .min (dp [col - 1 ], dp [col ]) + grid [row ][col ];
6658 }
6759 }
68- return dp [m - 1 ][n - 1 ];
60+
61+ // Return the minimum path sum for the last cell in the grid
62+ return dp [numCols - 1 ];
6963 }
7064}
0 commit comments