We can calculate buildings with an ocean view by iterating from the front and then keeping a monotonic stack — if we see a building that’s larger than previous buildings, we pop all smaller buildings we’ve seen so far.
At the end we return the buildings that still are in the stack.
class Solution:
def findBuildings(self, heights: List[int]) -> List[int]:
stack = []
for i, b in enumerate(heights):
while stack and b >= heights[stack[-1]]:
stack.pop()
stack.append(i)
return stack