-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainerWithMostWater.java
More file actions
89 lines (71 loc) · 2.2 KB
/
Copy pathContainerWithMostWater.java
File metadata and controls
89 lines (71 loc) · 2.2 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package arraylist;
import java.util.ArrayList;
public class ContainerWithMostWater {
public static int mostWater(ArrayList<Integer> height) {
// --- brute force - O(n^2) ---
// int maxWater = 0;
// for (int i = 0; i < height.size(); i++) {
// for (int j = i + 1; j < height.size(); j++) {
// int ht = Math.min(height.get(i), height.get(j));
// int width = j - i;
// int currWater = ht * width;
// maxWater = Math.max(maxWater, currWater);
// }
// }
// return maxWater;
// --- two pointer - O(n) ---
int maxWater = 0;
int lp = 0;
int rp = height.size() - 1;
while (lp < rp) {
int ht = Math.min(height.get(lp), height.get(rp));
int width = rp - lp;
int currWater = ht * width;
maxWater = Math.max(maxWater, currWater);
if (height.get(lp) < height.get(rp)) {
lp++;
} else {
rp--;
}
}
return maxWater;
}
public static void main(String[] args) {
ArrayList<Integer> height = new ArrayList<>();
height.add(1);
height.add(8);
height.add(6);
height.add(2);
height.add(5);
height.add(4);
height.add(8);
height.add(3);
height.add(7);
System.out.println(mostWater(height));
}
}
// For given n lines an x-axis, use 2 lines to form a container such that holds maximum water.
// height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
/*
Container With Most Water (LeetCode 11)
https://leetcode.com/problems/container-with-most-water/description/
class Solution {
public int maxArea(int[] height) {
int maxWater = 0;
int lp = 0;
int rp = height.length - 1;
while (lp < rp) {
int ht = Math.min(height[lp], height[rp]);
int width = rp - lp;
int currWater = ht * width;
maxWater = Math.max(maxWater, currWater);
if (height[lp] < height[rp]) {
lp++;
} else {
rp--;
}
}
return maxWater;
}
}
*/