Repository navigation
Expand file tree
/
Copy pathContainerWithMostWater.java
More file actions
55 lines (44 loc) · 1.58 KB
/
Copy pathContainerWithMostWater.java
File metadata and controls
55 lines (44 loc) · 1.58 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
49
50
51
52
53
54
55
import java.util.*;
public class ContainerWithMostWater {
// Brute Force Approach ! --> O(n^2)
static int solve(ArrayList<Integer> lines) {
int waterAmount = Integer.MIN_VALUE;
for(int i = 0; i < lines.size()-1; i++) {
int leftLine = lines.get(i);
for(int j = i+1; j < lines.size(); j++) {
int rightLine = lines.get(j);
int width = j - i;
int height = Math.min(leftLine, rightLine);
int currWater = width * height;
waterAmount = Math.max(currWater, waterAmount);
}
}
return waterAmount;
}
// 2-Pointer Approach !! --> O(n)
private static int solveUsing2Pointer(ArrayList<Integer> heights) {
int n = heights.size();
int leftPointer = 0;
int rightPointer = n-1;
int currWater = 0;
int maxWater = 0;
while(leftPointer <= rightPointer) {
int height = Math.min(heights.get(leftPointer), heights.get(rightPointer));
int width = rightPointer - leftPointer;
currWater = height*width;
maxWater = Math.max(currWater, maxWater);
if (heights.get(leftPointer) < heights.get(rightPointer))
leftPointer++;
else
rightPointer--;
}
return maxWater;
}
public static void main(String[] args) {
ArrayList<Integer> lines = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
int ans1 = solve(lines);
System.out.println(ans1);
int ans2 = solveUsing2Pointer(lines);
System.out.println(ans2);
}
}