-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0699-falling-squares.js
More file actions
60 lines (51 loc) · 1.75 KB
/
0699-falling-squares.js
File metadata and controls
60 lines (51 loc) · 1.75 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
58
59
60
/**
* Falling Squares
* Time Complexity: O(N^2)
* Space Complexity: O(N)
*/
var fallingSquares = function (positionsCollection) {
const storedSquaresMapping = new Map();
const resultHeights = [];
let overallHighestStack = 0;
for (
let squarePositionIndex = 0;
squarePositionIndex < positionsCollection.length;
squarePositionIndex++
) {
const currentSquareData = positionsCollection[squarePositionIndex];
const currentSquareLeftBoundary = currentSquareData[0];
const currentSquareSideLength = currentSquareData[1];
const currentSquareRightBoundary =
currentSquareLeftBoundary + currentSquareSideLength;
let heightBelowCurrentSquare = 0;
storedSquaresMapping.forEach(
(existingSquareProperties, existingSquareLeftBoundary) => {
const existingSquareSideLength = existingSquareProperties[0];
const existingSquareAbsoluteHeight = existingSquareProperties[1];
const existingSquareRightBoundary =
existingSquareLeftBoundary + existingSquareSideLength;
if (
currentSquareRightBoundary > existingSquareLeftBoundary &&
currentSquareLeftBoundary < existingSquareRightBoundary
) {
heightBelowCurrentSquare = Math.max(
heightBelowCurrentCurrentSquare,
existingSquareAbsoluteHeight,
);
}
},
);
const currentSquareAbsoluteHeight =
heightBelowCurrentSquare + currentSquareSideLength;
storedSquaresMapping.set(currentSquareLeftBoundary, [
currentSquareSideLength,
currentSquareAbsoluteHeight,
]);
overallHighestStack = Math.max(
overallHighestStack,
currentSquareAbsoluteHeight,
);
resultHeights.push(overallHighestStack);
}
return resultHeights;
};