-
Notifications
You must be signed in to change notification settings - Fork 43
/
ContainerWithMostWater.java
99 lines (84 loc) · 2.59 KB
/
ContainerWithMostWater.java
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
90
91
92
93
94
95
96
97
98
99
package LeetCodeJava.Greedy;
// https://leetcode.com/problems/container-with-most-water/
public class ContainerWithMostWater {
// V0
// IDEA : 2 POINTERS
public int maxArea(int[] height) {
if (height.length == 0 || height.equals(null)){
return 0;
}
int ans = 0;
int left = 0;
// NOTE : right as height.length - 1
int right = height.length - 1;
// either ">=" or ">" is OK for this problem, but for logic alignment, we use ">=" here
while (right >= left){
int leftVal = height[left];
int rightVal = height[right];
// NOTE !!! right - left, we get distance between left, right pointer
int amount = (right - left) * Math.min(leftVal, rightVal);
ans = Math.max(amount, ans);
if (rightVal > leftVal){
left += 1;
}else{
right -= 1;
}
}
return ans;
}
// V0'
// IDEA : BRUTE FORCE
public int maxArea_1(int[] height) {
if (height.length == 0 || height.equals(null)){
return 0;
}
int ans = 0;
for (int i = 0; i < height.length-1; i++){
for (int j = 1; j < height.length; j++){
int amount = (j - i) * Math.min(height[i], height[j]);
ans = Math.max(amount, ans);
}
}
return ans;
}
// V1
// IDEA : 2 POINTERS
public int maxArea_2(int[] height) {
if (height.length == 0 || height.equals(null)){
return 0;
}
int ans = 0;
int left = 0;
int right = height.length - 1;
while (right >= left){
int leftVal = height[left];
int rightVal = height[right];
int amount = (right - left) * Math.min(leftVal, rightVal);
ans = Math.max(amount, ans);
if (rightVal > leftVal){
left += 1;
}else{
right -= 1;
}
}
return ans;
}
// V2
// IDEA : 2 POINTERS
// https://leetcode.com/problems/container-with-most-water/editorial/
public int maxArea_3(int[] height) {
int maxarea = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int width = right - left;
maxarea = Math.max(maxarea, Math.min(height[left], height[right]) * width);
if (height[left] <= height[right]) {
left++;
} else {
right--;
}
}
return maxarea;
}
}