-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathMaximumPathSum.js
55 lines (52 loc) · 1.33 KB
/
MaximumPathSum.js
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
/**
* @author Anirudh Sharma
*
* Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c].
*
* Matrix [r+1] [c]
* Matrix [r+1] [c-1]
* Matrix [r+1] [c+1]
*
* Starting from any column in row 0, return the largest sum of any of the paths up to row N-1.
*/
const maximumPath = (matrix) => {
// Special case
if (matrix === undefined || matrix.length === 0) {
return 0;
}
// Order of the matrix
const N = matrix.length;
// Start from the second last row and move upward
for (let i = N - 2; i >= 0; i--) {
for (let j = 0; j < N; j++) {
// Current value
let current = matrix[i][j];
if (j > 0) {
current = Math.max(current, matrix[i + 1][j - 1]);
}
if (j < N - 1) {
current = Math.max(current, matrix[i + 1][j + 1]);
}
matrix[i][j] += current;
}
}
// Maximum sum
let maxSum = Number.MIN_VALUE;
for (let i = 0; i < N; i++) {
maxSum = Math.max(maxSum, matrix[0][i]);
}
return maxSum;
};
const main = () => {
let matrix = [
[348, 391],
[618, 193]
];
console.log(maximumPath(matrix));
matrix = [
[2, 2],
[2, 2]
];
console.log(maximumPath(matrix));
};
main();