Container With Most Water
Container With Most Water
Problem Description
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the $i^{th}$ line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Intuition
The area of water a container is determined by two factors:
- height: limited by the shorter of the two lines
- width: the distance between two vertical lines
Formula: area = width * min(height[left], height[right])
two pointer approach:
- Start with the widest container (left = 0, right = n-1), which gives us maximum width
- Calculate the current area and update the maximum
- To potentially find a larger area, we need to move the pointers inward.
Moving the pointer at the shorter line might increase the height, which could compensate for the reduced width → potential for larger area - Repeat until the two pointers meet
Algorithm
1 | class Solution { |
本部落格所有文章除特別聲明外,均採用CC BY-NC-SA 4.0 授權協議。轉載請註明來源 YouChen's Blog!