leet_11

题目: https://leetcode.com/problems/container-with-most-water/

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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.

 

n个非负的整数,a1,a2....an, 每一个都代表了一个坐标(i, ai). n条从点(i,ai) 到(i, 0)这样的垂直线。找到这样的两条线,和x轴形成一个容器,可以包含最多的水。

 

 

 
public static int maxArea(int[] height) {

if(null == height){
return 0;
}
int size = height.length;
int maxS = 0;

for(int i = 0; i < size; i++){
for(int j = i + 1;j < size; j++){
int maxSTemp = Math.min(height[i], height[j]) * (j - i);
if(maxSTemp > maxS){
maxS = maxSTemp;
}
}
}

return maxS;
}

public static int maxArea2(int[] height){

int max = 0;
int i=0, j=height.length-1;
while(i <= j){
int area = (j-i)*Math.min(height[i], height[j]);
max = Math.max(max, area);
if(height[j] >= height[i]){
i++;
}else{
j--;
}
}

return max;
}

 

 

 

Analysis

Initially we can assume the result is 0. Then we scan from both sides. If leftHeight < rightHeight, move right and find a value that is greater than leftHeight. Similarily, if leftHeight > rightHeight, move left and find a value that is greater than rightHeight. Additionally, keep tracking the max value.

container with most water

 

 

 

 

你可能感兴趣的:(leet_11)