by trinovantes · 4y ago · 0 comments
Of course trying to make this deduction during an actual interview when one or multiple people are watching you is an entirely different problem. Hopefully leetcode will give you enough practice to recognize patterns so that you don't need to think too deeply during interviews.
[3,2,100,100,2,3]
So you start on the outsides working in with your method, and you will stop at the two outermost 3s, because the 2 is less area, and never make it to the inner 100s. That's why the actual algorithm is to keep moving the pointers in until they meet, in a very specific way, keeping track of the maximum the whole time. It's not about actually finding the maximum and stopping early, it's about reducing the search space to O(n) from the naive O(n^2).
EDIT: However! There is a condition where h[n] <= len(h), which actually makes your method work! But you never mentioned that, so I think you may have gotten it by accident. :D
Like, with that condition, it becomes something like this:
[1,1,6,6,1,1]
and then stopping at the outer 1s is equivalent to making it in to the 6s.
I guess my issue is that I didn't example the conditions well enough. There's was a huge clue in there!
[3,2,100,100,2,3]
[2,100,100,2,3] (keep right 3, check if 2-3 has a larger area)
[100,100,2,3] (keep right 3, check if 100-3 has a larger area)
[100,100,2] (keep left 100, check if 100-2 has a larger area)
[100,100] (keep left 100, check if 100-100 has a larger area)