Medium Container With Most Water
39%
Accepted
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate
Have you met this question in a real interview? (i, ai). nvertical 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.
Yes
Example
Given
[1,3,2], the max area of the container is 2.
Note
You may not slant the container.
public class Solution {
/**
* @param heights: an array of integers
* @return: an integer
*/
public int maxArea(int[] heights) {
// write your code here
int maxArea = 0;
int start = 0, end = heights.length-1;
while(start < end){
maxArea = Math.max(maxArea, Math.min(heights[start], heights[end]) * (end - start));
if(heights[end] < heights[start]){
end--;
} else start++;
}
return maxArea;
}
}
No comments:
Post a Comment