Container With Most Water

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.

Example

Given [1,3,2], the max area of the container is 2.

Notes:

  1. Two pointers
  2. Calculate the area formed by the two pointers
  3. Get max when moving
    public int maxArea(int[] heights) {
        if (heights == null || heights.length == 0) {
            return 0;
        }

        int i = 0;
        int j = heights.length-1;
        int max = 0;
        while(i < j) {
            max = Math.max(max, Math.min(heights[i], heights[j]) * (j-i));
            if (heights[i] < heights[j]) {
                i++;
            } else {
                j--;
            }
        }

        return max;
    }

results matching ""

    No results matching ""