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.spa
給你一個頂點數組,例如{4,7,9},這個定點數組表明直角座標系上三個點,(1,4),(2,7),(3,9),而後過這三個點,分別做垂直於X軸的線段,例如對於(1,4),線段的兩個端點爲(1,4)和(1,0),而後,咱們能夠獲得三條垂直於X軸的線段。從這些線段中找出一對組合,使得,這對組合的 橫座標之差 乘以 兩條線段中較短者的長度 的乘積最大。指針
解題思路:code
最大盛水量取決於兩邊中較短的那條邊,並且若是將較短的邊換爲更短邊的話,盛水量只會變少。因此咱們能夠用兩個頭尾指針,計算出當前最大的盛水量後,將較短的邊向中間移,由於咱們想看看能不能把較短的邊換長一點。這樣一直計算到左邊大於右邊爲止就好了orm
先拿最左邊的線段和最右邊的線段做爲組合,計算出乘積,而後,找二者中較爲短的一方,慢慢向中間靠攏。舉個例子,{4,3,7,2,9,7},先計算4和7的組合的乘積,而後找二者中比較小的一方,這裏是4,讓它向中間靠攏,向前走一步是3,但3比4小,因此計算3和7的組合是沒有意義的,因此,繼續向中間靠攏,發現了7,7比4大,因此有可能會獲得比原來更大的面積,所以計算7和7的組合的乘積。blog
重複這個過程,直至左邊的工做指針大於等於右邊的工做指針get
public class Solution { public int maxArea(int[] height) { int lpoint = 0, rpoint = height.length - 1; int area = 0; while (lpoint < rpoint) { area = Math.max(area, Math.min(height[lpoint], height[rpoint]) * (rpoint - lpoint)); if (height[lpoint] > height[rpoint]) rpoint--; else lpoint++; } return area; } }
class Solution(object): def maxArea(self, height): """ :type height: List[int] :rtype: int """ size = len(height) # the size of height maxm = 0 # record the most water j = 0 k = size - 1 while j < k: if height[j] <= height[k]: maxm = max(maxm,height[j] * (k - j)) j += 1 else: maxm = max(maxm,height[k] * (k - j)) k -= 1 return maxm