Explained step by step
There is a list ht with the height of some vertical boards. Any 2 boards form a container, and its capacity is its area: the shorter board sets the height, and the index difference sets the width. cap[i, j] = min(ht[i], ht[j]) × (j − i). You look for the pair with the highest capacity. With ht = [1, 8, 6, 2, 5, 4, 8, 3, 7], the best is the pair at indexes 1 and 8: min(8, 7) × 7 = 49.
The strategy uses 2 pointers. Start with i at 0 and j at the last board. At each step compute cap[i, j] and keep it if it is the largest; then move the pointer at the shorter board inward. Repeat until i and j meet. With ht = [1, 8, 6, 2, 5, 4, 8, 3, 7]: [0, 8] gives 8, i moves; [1, 8] gives 49, j moves; and so on until it ends with 49.
Each pair of boards is a state, [i, j]. With n boards there are n(n − 1) ÷ 2 pairs: with 9 boards, 36. The most direct way is to try them all and keep the largest, but it costs O(n²): with 100,000 boards, about 5 billion pairs. The greedy finds the maximum in O(n) visiting each board once.
The loop runs at most n times, because each round brings the pointers 1 spot closer: the time is O(n). Only 3 variables are used, i, j and res, so the extra memory is O(1). With 1 million boards, 1 million steps and 3 numbers, against 500 billion pairs trying them all.
If in state [i, j] board i is the shorter, moving j inward always shrinks: the width drops by 1, and the height stays or drops, because the shorter still rules. Moving i inward also drops the width, but the height can rise if the new board is taller. That is why the only move that can improve is moving the shorter board.
The greedy is fast because each move skips states. In [i, j], if i is the shorter, moving i skips cap[i, i + 1], cap[i, i + 2], ..., cap[i, j − 1]. Those are exactly the states you would reach by moving j inward, and we saw that always shrinks. None of them can be the optimum, so skipping them does not lose the maximum.