描述
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.
分析
题目在时间复杂度O(n2)下一个两次循环遍历即可,但需要时间复杂度O(n)的下完成,通过分析,可以采用左右夹逼的方式来做,如果说左边数大于右边的数,则右边向左偏移一位,否则左边向右偏移一位
代码
package com.lilei.myes.es.pack1108; public class ContainerWithMostWater { public static void main(String[] args) {
System.out.println(cwmw(new int[]{3,2,3,4,5})); }
static int cwmw(int[] array){
int area = 0; int left = 0; while(array[left] <=0){
left++;
} int right = array.length-1; while(array[right] <=0){
right--;
} while(left < right){
int height = array[left]>array[right]?array[right] : array[left]; area = Math.max(area, height * (right - left)); if (array[left] > array[right])
array[left] = right--;
else
array[left] = left++;
} return area;
} }