Skip to content

Commit c831b5e

Browse files
committed
Code for Container With Most Water
1 parent 91e93df commit c831b5e

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

Java/containerWithMostWater.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import java.util.*;
2+
import java.util.Scanner;
3+
4+
public class ContainerWithMostWater {
5+
6+
public static void main(String[] args) {
7+
8+
Scanner sc = new Scanner(System.in);
9+
10+
// Get inputs
11+
System.out.println("Enter the number of lines:");
12+
int n = sc.nextInt();
13+
14+
int[] height = new int[n];
15+
System.out.println("Enter the heights of the lines:");
16+
for (int i = 0; i < n; i++) {
17+
height[i] = sc.nextInt();
18+
}
19+
20+
int maxArea = findMaxArea(height);
21+
22+
System.out.println("The maximum water that can be contained is: " + maxArea);
23+
}
24+
25+
26+
public static int findMaxArea(int[] height) {
27+
int left = 0;
28+
int right = height.length - 1;
29+
int maxArea = 0;
30+
31+
while (left < right) {
32+
int width = right - left;
33+
int minHeight = Math.min(height[left], height[right]);
34+
int area = width * minHeight;
35+
36+
maxArea = Math.max(maxArea, area);
37+
38+
// Move the pointer pointing to the smaller line
39+
if (height[left] < height[right]) {
40+
left++;
41+
} else {
42+
right--;
43+
}
44+
}
45+
46+
return maxArea;
47+
}
48+
}
49+

0 commit comments

Comments
 (0)