𝐂𝐨𝐧𝐭𝐚𝐢𝐧𝐞𝐫 𝐖𝐢𝐭𝐡 𝐌𝐨𝐬𝐭 𝐖𝐚𝐭𝐞𝐫 || 𝐋𝐞𝐞𝐭𝐜𝐨𝐝𝐞 𝐀𝐫𝐫𝐚𝐲 𝐏𝐫𝐨𝐛𝐥𝐞𝐦


 

Given an array of height n in this problem.  We have a bar graph that has n verticle lines of a given array and has endpoints of i will be height[i].

We have to find the area between the 2 lines on the x-axis such they create a container that fills the most water.

You have to return the maximum amount of water a container can store.

Note You cannot lean the container to maximize the area of container.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: In this bar graph, we find the maximum area between two verticle lines is 49 (represented by blue area).Given array is height=[1,8,6,2,5,4,8,3,7]. 

Example 2:

Input: height = [1,1]
Output: 1

 

Constraints:

  • n == height.length
  • 2 <= n <= 105
  • 0 <= height[i] <= 104

Effective solution:


Approach: Given a range of container boundary line heights, find the maximum amount of water that can be stored in the container. So start with the first and last element and check the amount of water it can contain and store that container. Now the question arises whether there are any better boundaries or lines which can contain the maximum of water. So there is a smart way to find out. Initially, there are two indices, the first and last index pointing to the first and last element (which acts as the container boundary), if the value of the first index is less than the value of the last index increment the first index, otherwise decrement the last index. Since the loss of width is constant, following the above procedure can lead to an optimal response.

𝐉𝐚𝐯𝐚 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧

Code:-  class Solution {
    public int maxArea(int[] height) {
        int l=0;
        int e=height.length-1;
        int max=0;
        while(l<e){
            int min_h=Math.min(height[l],height[e]);
            int curr_area=min_h*(e-l);
            max=Math.max(max,curr_area);
            if(height[l]<height[e]) l++;
            else e--;
        }
        return max;
    }
}


Success
Details 
Runtime: 5 ms, faster than 65.65% of Java online submissions for Container With Most Water.
Memory Usage: 81.5 MB, less than 22.76% of Java online submissions for Container With Most Water.
Post a Comment (0)
Previous Post Next Post