题目描述:
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.
import java.io.*; import java.util.*; public class Solution { public static int maxArea(int[] height) { int len=height.length; int i=0,j=0,r=0; int len1=len-1; int[] c=new int[len1]; for(i=0;i<len1;i++) c[i]=0; for(i=0;i<len1;i++) { for(j=i+1;j<len;j++) { c[i]=Math.min(height[i],height[j])*(j-i); if(c[i]>r) r=c[i]; } } return r; } public static void main(String[] args) { Scanner input=new Scanner(System.in); int[] h={1,2,1}; int r=maxArea(h); System.out.println(r); } }
暴力遍历。
超时。
应该只能有一层循环。
【待更新】
来自大神的代码。