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