11. Container With Most Water

Medium
Given n non-negative integers a1a2, ..., a, 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 and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Solution: two pointer

Note 1 : When you consider a1 and aN, then the area is (N-1) * min(a1, aN).
Note 2 : The base (N-1) is the maximum possible.
  • This implies that if there was a better solution possible, it will definitely have the Height greater than min(a1, aN).
     Base * Height > (N-1) * min(a_1, a_N)
  • We know that, Base min(a1, aN)
    This means that we can discard min(a1, aN) from our set and look to solve this problem again from the start.
  • If a1 < aN, then the problem reduces to solving the same thing for a2, aN.
  • Else, it reduces to solving the same thing for a1, aN-1
    public int maxArea(int[] height) {
        if(height == null || height.length == 0){
            return 0;
        }
        int right = height.length - 1;
        int left = 0;
        int max = 0;
        while(left <= right){
            int area = Math.min(height[left], height[right]) * (right - left);
            max = Math.max(max, area);
            if(height[left] < height[right]){
                left++;
            }else{
                right--;
            }
        }
        return max;
    }



Comments

Popular posts from this blog

MockInterview:785. Is Graph Bipartite?

geeksforgeeks:findFind zeroes to be flipped so that number of consecutive 1’s is maximized

94.Binary Tree Inorder Traversal