Friday, February 7, 2014

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.

Solution:
1. Brute-Force: select any two vertical lines. O(n^2).
2. Use two pointers, left and right. Left start from the beginning to right while right starts from the end to left. area = (distance * min(height(left), height(right))). When they are approaching each other, distance is decreasing, so if we want to increase the area, we need to increase min(height(left), height(right)). 

public class Solution {
    public int maxArea(int[] height) {
        int maxArea = 0;
        int area = 0;
        int left = 0;
        int right = height.length - 1;
        // iterate all positions for its max area
        while(left < right){
            if(height[left] < height[right]){
                area = (right - left) * height[left];
                left++;
            }
            else{
                area = (right - left) * height[right];
                right--;
            }
            if(area > maxArea) maxArea = area;
        }
        return maxArea;
    }
}

No comments:

Post a Comment