I’ve been working on this problem for a bit, and I seem to be stuck on finding any sort of solution. I know that the solution for O(N) has to deal with stacks, but I can’t figure out how to properly utilize stacks for this problem.
Some things I’ve thought of:
- I don’t think the widths matter at all, because the posters can be infinitely long, and just replacing all widths with 1 yields the same result (not 100% sure though)
- The O(N^2) solution is to find the minimum height of the buildings, then subtract that height from all of the other heights. In essence, this would separate the buildings into their “layers.” Then, the answer would just be the number of times this process has to happen for all buildings to have a height of 0.
I am stuck on what the stack’s function actually will be. But more importantly, I am confused on when we should pop from the stack and what we should do with the top element of the stack.
Thank you in advance for any help!
EDIT: I just realized that the O(N^2) solution does not work after all. For example, if we had the input:
3
1 3
1 1
1 3
The program would output 2, when it should really be 3.