11. Container With Most Water - Medium
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
two pointers
p1, p2分別從首、尾開始掃描陣列,同時計算面積。長方形面積中的底是一直在減小的(每次減少1),高是兩條邊中較短的邊長,如果當前p1對應的邊長小於p2對應的邊長,應該保留較長的邊(即p2),p2不變,p1向右移動,面積增大的可能性更大(理由:如果保留p1而移動p2,如果p2移動後變大,邊長還是取較短的p1,如果p2移動後變小,邊長取這個較小的新邊長。新的邊長 <= p1,即,移動後邊長不會增加;但是如果保留p2而移動p1的話,如果p1移動後變大,邊長可以取新的較大的邊長或p2,即,移動後邊長有增加的可能)。反之則應該移動p2。
時間:O(N),空間:O(1)
class Solution { public int maxArea(int[] height) { int p1 = 0, p2 = height.length - 1; int max = 0; while(p1 < p2) { int area = (p2 - p1) * Math.min(height[p1], height[p2]); max = Math.max(max, area); if(height[p1] < height[p2]) p1++; else p2--; } return max; } }