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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.

Example:

Input:  arr:{4,3,2,1,4}
Output: 16

Approach

Java

public class ContainerWithMostWater {
    public static void main(String[] args) {
        int height[] = { 43214 };
        System.out.println(maxArea(height));
    }

    static int maxArea(int[] height) {
        int n = height.length;
        int low = 0, high = n - 1, res = 0;
        while (low < high) {
            res = Math.max(res, Math.min(height[low], height[high]) 
                    * (high - low));
            if (height[low] < height[high])
                low++;
            else
                high--;
        }
        return res;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

int maxArea(vector<int>& height
{
    int n=height.size();
    int low=0,high=n-1,res=0;
    while(low<high)
         {
            res=max(res,min(height[low],height[high])*(high-low));
            if(height[low]<height[high])
                    low++;
            else
                high--;
         }
        return res;
}
int main()
{
   vector<int> height ={4,3,2,1,4};
   cout<<maxArea(height);
   return 0;
}



No comments:

Post a Comment