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.指針
時間 O(N) 空間 O(N)code
最大盛水量取決於兩邊中較短的那條邊,並且若是將較短的邊換爲更短邊的話,盛水量只會變少。因此咱們能夠用兩個頭尾指針,計算出當前最大的盛水量後,將較短的邊向中間移,由於咱們想看看能不能把較短的邊換長一點。這樣一直計算到左邊大於右邊爲止就好了。orm
若是將較短的邊向中間移後,新的邊還更短一些,其實能夠跳過,減小一些計算量leetcode
public class Solution { public int maxArea(int[] height) { int left = 0, right = height.length - 1, maxArea = 0; while(left < right){ // 每次更新最大面積(盛水量) maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left)); // 若是左邊較低,則將左邊向中間移一點 if(height[left] < height[right]){ left++; // 若是右邊較低,則將右邊向中間移一點 } else { right--; } } return maxArea; } }