-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path082-path-sum-three-ways.js
More file actions
57 lines (47 loc) · 1.24 KB
/
082-path-sum-three-ways.js
File metadata and controls
57 lines (47 loc) · 1.24 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
57
/**
* Path Sum Three Ways
* Time Complexity: O(N²)
* Space Complexity: O(N)
*/
function processData(input) {
const lines = input.trim().split('\n');
let idx = 0;
const N = parseInt(lines[idx++], 10);
const matrix = [];
for (let i = 0; i < N; i++) {
matrix.push(lines[idx++].trim().split(' ').map(BigInt));
}
let dp = new Array(N);
for (let r = 0; r < N; r++) {
dp[r] = matrix[r][0];
}
for (let c = 1; c < N; c++) {
for (let r = 0; r < N; r++) {
dp[r] = dp[r] + matrix[r][c];
}
for (let r = 1; r < N; r++) {
if (dp[r] > dp[r - 1] + matrix[r][c]) {
dp[r] = dp[r - 1] + matrix[r][c];
}
}
for (let r = N - 2; r >= 0; r--) {
if (dp[r] > dp[r + 1] + matrix[r][c]) {
dp[r] = dp[r + 1] + matrix[r][c];
}
}
}
let result = dp[0];
for (let r = 1; r < N; r++) {
if (dp[r] < result) result = dp[r];
}
console.log(result.toString());
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});