Repository navigation
Expand file tree
/
Copy pathMaxPath.java
More file actions
56 lines (41 loc) · 1.34 KB
/
Copy pathMaxPath.java
File metadata and controls
56 lines (41 loc) · 1.34 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package practise.leetCode;
public class MaxPath {
public static void main(String[] args) {
int[][] matrix = {
{5, 1, 2, 3},
{4, 8, 1, 2},
{3, 2, 9, 4},
{1, 7, 6, 5}
};
System.out.println("Maximum Path Sum: " + maxPath(matrix));
}
public static int maxPath(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
// Start from bottom-left
int[][] dp = new int[rows][cols];
dp[rows - 1][0] = matrix[rows - 1][0];
// First column - can only move UP
for (int i = rows - 2; i >= 0; i--) {
dp[i][0] = matrix[i][0] + dp[i + 1][0];
}
// Remaining cells
// From each cell, we can come from:
// 1. Bottom -> moving UP
// 2. Left -> moving RIGHT
for (int i = rows - 2; i >= 0; i--) {
for (int j = 1; j < cols; j++) {
dp[i][j] = matrix[i][j]
+ Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(dp[i][j] + " ");
}
System.out.println();
}
// Top-right is the destination
return dp[0][cols - 1];
}
}