LeetCode Daily Question 21
May 6th 2022
5 月 5 日 每日一题
题目:11. Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith 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.
1 | Input: height = [1,8,6,2,5,4,8,3,7] |
思路
本题是关于双指针和贪心的题目,Greedy 的逻辑为:从可能最大的宽度起始,如果左边小,则 left++,如果右边小则 right–。因为水面高度永远取最小,所以如果移动大的一边,体积必然下降。如果 greedy 后得出的体积比当前的 maxArea 大,则修改当前 maxArea。
代码
1 | class Solution { |