Wednesday, January 28, 2015

LeetCode: Container with most water

I was trying to think about this problem from 2 days but really couldn't reach the optimal solution. I really loved the problem when I studied the solution. Here's the problem:

https://oj.leetcode.com/problems/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.

Note: You may not slant the container.

The brute force solution is easy to think. Just check the area for each pair of starting and ending line and find the pair with maximum area. Running time is O(n^2)

However, this problem has a very neat O(n) solution. Start with two pointers left = 0 and right = n-1. Calculate it's area and see if it is maximum. Now if height of left pointer is less than the height of the right pointer, increment left, else increment right. Now this part is difficult to understand. Here's the intuition: if the height of the left pointer is less than the height of the right pointer, even if you move the right pointer you cannot do any better; because even if the new right is even bigger the left height will be minimum of the two. And in the other case if the new right is even smaller, it anyhow cannot make any improvement. So why increment left? If we reach a new left height which is larger then we can get a new maximum area. Keep doing this till left < right.

Here's the code which got accepted in LeetCode Online Judge.

class Solution {
public:
    int maxArea(vector<int> &height) {
        int left = 0, right = height.size()-1;
        int max_area = 0, cur_area;
        while(left < right){
            cur_area = (right-left)*min(height[left], height[right]);
            max_area = max(cur_area, max_area);
            if(height[left] < height[right])
                left++;
            else
                right--;
        }
        return max_area;
    }
};

No comments:

Post a Comment