Sunday, February 24, 2013

[LeetCode] Container with Most Water

Thought:
Calculate from both side leads to a O(n) solution.

Code:
public class Solution {
    public int maxArea(int[] height) {
        int i = 0;
        int j = height.length - 1;
        int result = 0;
        while( i < j ){
            result = Math.max( Math.min(height[i], height[j]) * (j - i), result);
            if(height[i] < height[j]){
                i++;
            }else{
                j--;
            }
        }
        return result;       
    }
}

No comments:

Post a Comment