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. html
Note: You may not slant the container. java
https://oj.leetcode.com/problems/container-with-most-water/ .net
思路1:O(n^2)複雜窮舉全部的狀況,too young too simple. 指針
思路2::兩個指針i,j分別指向首位,選擇兩者中小的向中間移動,同時更新最大值。這個想法的基礎是,若是i的長度小於j,若是移動j,短板在i,不可能找到比當前記錄的area更大的值了,只能經過移動i來找到新的可能的更大面積。 code
public class Solution { public int maxArea(int[] height) { int n = height.length; int maxA = 0; int curA = 0; int i = 0, j = n - 1; while (i < j) { if (height[i] <= height[j]) { curA = Math.abs(j - i) * height[i]; if (curA > maxA) maxA = curA; i++; } else { curA = Math.abs(j - i) * height[j]; if (curA > maxA) maxA = curA; j--; } } return maxA; } public static void main(String[] args) { System.out.println(new Solution().maxArea(new int[] { 2, 2, 2 })); System.out.println(new Solution().maxArea(new int[] { 1, 2, 3 })); System.out.println(new Solution().maxArea(new int[] { 2, 3, 3 })); } }
參考: orm
http://blog.csdn.net/wzy_1988/article/details/17248209 htm
http://www.cnblogs.com/zhaolizhen/p/Containerwater.html blog