11. Container With Most Water
source: https://leetcode.com/problems/container-with-most-water/
Question
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.
思路
这题和42题看起来有点像,都是去接水,但是两者其实差别很大,一题是去算总共能接的水,一题是去算最优情况。但类似的是,他们都可以用双指针去做。
从初始情况开始,宽度是最大的,之后无论怎么动,宽度都是在减小。除非两者高度的较小值变大。
所以优先去移动高度较小的一边。
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function(height) {
let ret = 0;
let left = 0;
let right = height.length - 1;
while (left < right) {
const width = right - left;
const length = Math.min(height[left], height[right]);
const volume = width * length;
ret = Math.max(volume, ret);
if (height[left] < height[right]) left++;
else right--;
}
return ret;
};
总结
链表的while遍历方式应用很普遍。