Container With Most Water — Leetcode
Topic: Array
Difficulty: Medium
Question Number: 11
Problem statement:
You are given an integer array height
of length n
. There are n
vertical lines drawn such that the two endpoints of the ith
line are (i, 0)
and (i, height[i])
.
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: 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 2:
Input: height = [1,1]
Output: 1
Explanation:
This is a quite confusing question but easy too. Let's first understand this question with a brute-force approach.
Checking for height
First, from the left [0] and right[1] find the area of water that can be filled.
height[0] = 1
height[1] = 8
Water can be filled up to height ‘1’ only. so, Height= 1
Checking for width
distance between left[0] and right[1] is 1
right-left => 1–0 = 1
so, Width = 1
Checking for area
h x w
1 x 1 = 1
Similarly, the left[0] will be checked with the right[2,3,4,5,6,7,8].
Then, left[1,2,3,4,5,6,7,8] will be checked with right[0,1,2,3,4,5,6,7,8]
After, calculating the areas from each possible bar. Writing them down in a matrix form table to find the maximum area.
MAX AREA = 49
but, the time complexity is O(n²)
Not a good approach :(
Let’s try the same question with the optimized approach.
- First mark the left-right pointers where we can get the maximum width. Which always going to be the first number of the array and the last number of the array.
- Find the area of the water and store the value in the area variable
- Follow
if (height[left] <= height[right])
left++;
else
right — ;
and move the left-right pointer accordingly. - from all the areas calculated, find the max area
As you can notice from the above approach, we minimized and optimized the way of getting the answer.
Time complexity- O(n)
Code:
class Solution {
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int maxArea = 0;
while (left <= right) {
int area = Math.min(height[left], height[right]) * (right - left);
maxArea = Math.max(maxArea, area);
if (height[left] <= height[right]) {
left++;
} else {
right--;
}
}
return maxArea;
}
}
Thank you
Oshi Raghav