2014年4月8日 星期二

[LeetCode] Container With Most Water

Problems: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.
Solutions:O(n)

public class Solution {
    public int maxArea(int[] height) {
        int start = 0;
        int end = height.length -1;
        int max = 0;
        int leftheight = 0;
        int rightheight = 0;
        while(end > start){
             if(height[start] < leftheight){
                        start++;
                        continue;
             }
             if(height[end] < rightheight){
                        end--;
                        continue;
             }
            
             leftheight = Math.max(leftheight,height[start]);
             rightheight = Math.max(rightheight,height[end]);
             int wall = Math.min(leftheight,rightheight); 
             max = Math.max(max, (end-start)*wall);
            
             if(wall == leftheight)
             start++;
             else
             end--;
        }
        return max;
    }
}
Key concept: From both sides move inside to make largest rectangle area 

沒有留言:

張貼留言