Tuesday, August 25, 2015

Container With Most Water

Problem Description
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
In this problem, we use 2 pointers, one runs from the 0, one runs backward.

public class Solution {
    public int maxArea(int[] height) {
        //we assume the array height.length > 0
        int max = 0;
        int area;
        for(int i=0, j=height.length-1; i<j;){
            
            if(height[i] > height[j]){
                area = (j-i) * height[j];
                j--;
            }else {
                area = (j-i) * height[i];
                i++;
            }
            if(area > max) max = area;
        }
        return max;
    }
}

No comments:

Post a Comment