day 08
treetop tree house
approach
for every row and column, a monotonic stack finds the index of the first tree at least as tall in each of the four directions, or -1 if there isn't one. that gives four grids: left to right, right to left, top to bottom and bottom to top.
part 1 counts the trees where at least one direction has no blocker, so they're visible from that edge. part 2 replaces each missing blocker with the grid edge, turns the indices into viewing distances, and takes the largest product of the four. the rust version is a port; there's also a sync-conflict copy of it in the folder with an extra comparison parameter.
the trick
"first taller tree in this direction" is the classic next-greater-element problem, which a stack solves in one pass per line.
python
def next_largest(arr):
res = [-1 for _ in range(len(arr))]
s = []
for i in range(len(arr)):
while s and arr[s[-1]] <= arr[i]:
res[s.pop()] = i
s.append(i)
return res