11. Container With Most Water
I solved this problem using C++.
My idea: two for
loops to iterate through the vector height
and calculate the area of the container.
However, this solution is not efficient because it has a time complexity of O(n^2).
1 |
|
use two pointers
- set
l
to 0 andr
to the size of the vectorheight
- 1. - use a while loop to iterate through the vector.
- set
area
to the minimum ofheight[l]
andheight[r]
multiplied byr - l
. - move the pointer of the smaller height to the next position.
- return the maximum area.
1 | class Solution { |
Why move the pointer of the smaller height?
Because the area is determined by the smaller height, moving the pointer of the smaller height may lead to a larger area.
If we move the pointer of the larger height, the area will not change, but we may miss a larger area.
conclusion
Today’s Saturday early morning, and I drank a tin of beer just now😏
Maybe I should stop drinking beer and start go to bed earlier😥…