Container with the most water.

Sneha Michelle,Two Pointers

Leetcode link

Container with the most water (opens in a new tab)

Problem Statement

There is an array of heights of a set of containers of water. We need to find the water containers that can hold the highest area of water.

Here, the output is 49 because, 7 is the minimum height, and there are 7 spaces in the x axis. 7*7=49


Algorithm


Code

class Solution {
    public int maxArea(int[] height) {
       int left = 0; 
       int right = height.length-1;
       int area = 0;
       int maxarea=0;
       while (left<right){
           area = (right-left) *(Math.min(height[left],height[right]));
           maxarea = Math.max(maxarea, area);
           if (height[left]<height[right]){
               left = left+1;
           }
           else{
               right = right-1;
           }
       }
 
       return maxarea;
    }
}