-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsunset-views.js
More file actions
26 lines (22 loc) · 789 Bytes
/
Copy pathsunset-views.js
File metadata and controls
26 lines (22 loc) · 789 Bytes
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
//SUNSET VIEWS
// time O(n) where n is the number of buildings
// space O(n)
function sunsetViews(buildings, direction) {
let currentMaxHeight = 0;
const stack = [];
let currentIdx = direction === "EAST" ? buildings.length - 1 : 0;
const step = direction === "EAST" ? -1 : 1;
while (currentIdx >= 0 && currentIdx < buildings.length) {
let buildingHeight = buildings[currentIdx];
if (buildingHeight > currentMaxHeight) {
stack.push(currentIdx);
currentMaxHeight = buildingHeight;
}
currentIdx += step;
}
if (direction === "EAST") return stack.reverse(); // time O(n)
return stack;
}
const buildings = [3, 5, 4, 4, 3, 1, 3, 2];
const direction = "EAST";
console.log(sunsetViews(buildings, direction));