[
stack
monotonic deque
greedy
]
Leetcode 1762 Buildings With an Ocean View
Problem statement
https://leetcode.com/problems/buildings-with-an-ocean-view/
Solution
The idea is to start from the ocean and add elements to stack only if they bigger than last element in the stack. In the end return reversed stack.
Complexity
Time and space complexity is O(n)
.
Code
class Solution:
def findBuildings(self, H):
n, ans = len(H), []
for i in range(n-1, -1, -1):
if not ans or H[i] > H[ans[-1]]:
ans += [i]
return ans[::-1]