Max Water Container
You are given an integer array heights where heights[i] represents the height of the ithi^{th}ith bar.
You may choose any two bars to form a container. Return the maximum amount of water a container can store.
Example 1:
Input: height = [1,7,2,5,4,7,3,6]
Output: 36
Example 2:
Input: height = [2,2,2]
Output: 4
Constraints:
2 <= height.length <= 1000
0 <= height[i] <= 1000
Solution
In a greedy strategy, a given container can have larger area when there exists a higher bar in it, beacause lower bar with shorter distance will definitely have smaller area. Also, for a given container, when we shrink the length between its endpoints, they area might become large only when we move the shorter bar.
Therefore, we can first take the 0 and n-1 bar as the endpoints, and move the shorter bar every time to gain a maximum.
Code
class Solution:
def maxArea(self, heights: List[int]) -> int:
ans = 0
le = 0
ri = len(heights)-1
while le < ri:
ans = max(ans, min(heights[le], heights[ri])*(ri-le))
if heights[le] < heights[ri]:
le += 1
else:
ri -= 1
return ans


被折叠的 条评论
为什么被折叠?



