-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0120-triangle.js
More file actions
56 lines (48 loc) · 1.45 KB
/
0120-triangle.js
File metadata and controls
56 lines (48 loc) · 1.45 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
/**
* Triangle
* Time Complexity: O(R^2)
* Space Complexity: O(R)
*/
var minimumTotal = function (triangle) {
if (triangle.length === 1) {
return triangle[0][0];
}
let minPathSumsToPreviousRow = [triangle[0][0]];
for (
let currentRowIndex = 1;
currentRowIndex < triangle.length;
currentRowIndex++
) {
let currentTriangleRowValues = triangle[currentRowIndex];
let minPathSumsToCurrentRow = new Array(currentTriangleRowValues.length);
minPathSumsToCurrentRow[0] =
minPathSumsToPreviousRow[0] + currentTriangleRowValues[0];
for (
let positionInCurrentRow = 1;
positionInCurrentRow < currentRowIndex;
positionInCurrentRow++
) {
minPathSumsToCurrentRow[positionInCurrentRow] =
currentTriangleRowValues[positionInCurrentRow] +
Math.min(
minPathSumsToPreviousRow[positionInCurrentRow - 1],
minPathSumsToPreviousRow[positionInCurrentRow],
);
}
minPathSumsToCurrentRow[currentRowIndex] =
minPathSumsToPreviousRow[currentRowIndex - 1] +
currentTriangleRowValues[currentRowIndex];
minPathSumsToPreviousRow = minPathSumsToCurrentRow;
}
let minimumFinalSum = Infinity;
for (
let pathIndex = 0;
pathIndex < minPathSumsToPreviousRow.length;
pathIndex++
) {
if (minPathSumsToPreviousRow[pathIndex] < minimumFinalSum) {
minimumFinalSum = minPathSumsToPreviousRow[pathIndex];
}
}
return minimumFinalSum;
};