Skip to content

Commit 1d6e962

Browse files
committed
Java solution for Container_with_most_water
1 parent 2f5f578 commit 1d6e962

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Question : https://leetcode.com/problems/container-with-most-water/
2+
3+
// Example
4+
/**
5+
* Example 1:
6+
* Input: height = [1,8,6,2,5,4,8,3,7]
7+
* Output: 49
8+
* Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
9+
* In this case, the max area of water (blue section) the container can contain is 49.
10+
*
11+
* Example 2:
12+
* Input: height = [1,1]
13+
* Output: 1
14+
*/
15+
16+
import java.util.*;
17+
18+
class Solution {
19+
public static int maxArea(int[] height) {
20+
int sum = 0, l = 0, r = height.length-1;
21+
22+
while(l<r) {
23+
24+
// iterate from both side and find min height.
25+
// It will provide the min. water storage by forming a shape of container.
26+
27+
int temp = Math.min(height[l], height[r]);
28+
sum = Math.max(sum, (r-l)*temp);
29+
30+
// Increment/Decrement from left/right side to find next largest container.
31+
32+
if(height[r]>height[l])
33+
l++;
34+
else
35+
r--;
36+
}
37+
38+
return sum;
39+
}
40+
41+
public static void main(String[] args) {
42+
Scanner sc = new Scanner(System.in);
43+
44+
int n = sc.nextInt();
45+
int[] height = new int[n];
46+
47+
for(int i = 0; i < n; i ++)
48+
height[i] = sc.nextInt();
49+
50+
System.out.println( maxArea(height) );
51+
52+
sc.close();
53+
}
54+
}

0 commit comments

Comments
 (0)