Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
不知道爲啥,這道題是我在leetcode裏印象最深的一道題。
記得上次錯,吭哧吭哧了好半天,交出來個錯誤答案。後來好像就放棄了。
這次的進步是,30秒送了個brute force竟然還沒超時。果然o(n方)也不是不可忍受的存在啊。既然能brute force, 那就先來一下子嘛。
然後就看了答案。。哈哈哈哈。真的是對於array的奇形怪狀的解法喪失了自己去琢磨的堅持。但是居然很make sense啊!!
所以拿到一道題,尤其是array, 如果想優化,就要想,哪些掃描是沒必要的。就比如這道題,兩個棍兒一個長,一個短,那麼那成短的存在就沒啥意義啊對不。睡覺!!
class Solution {
public int maxArea(int[] height) {
if (height == null || height.length == 0) return 0;
int res = 0;
int left = 0, right = height.length - 1;
while(left < right){
res = Math.max(res, Math.min(height[left], height[right]) * (right - left));
if (height[left] < height[right]) left ++;
else right --;
}
return res;
}
}