Skip to content

Commit 4bd04ae

Browse files
committed
feat: solve container with most water
1 parent 7eae790 commit 4bd04ae

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
class Solution {
2+
public int maxArea(int[] height) {
3+
/**
4+
1. understanding
5+
- with two pair of line, each can contain "min(line1,line2) * (distance)" mount of water
6+
- find maximum amount of water can contain
7+
2. strategy
8+
- brute force
9+
- for each pair of lines, calculate amount and update maximum amount.
10+
- it can takes O(N), where N is the count of lines.
11+
- N is 10^5 at most, so it can takes 10^10, which can takes about 10 seconds
12+
- you need to swap out unnecessary calculation
13+
- so, let's find a unnecessary calculation in this problem.
14+
3. complexity
15+
- time: O(N)
16+
- space: O(1)
17+
*/
18+
int l = 0;
19+
int r = height.length - 1;
20+
int maxAmount = amountOf(height, l, r); // Math.min(height[l], height[r], r-l);
21+
while (l < r) { // O(N)
22+
maxAmount = Math.max(maxAmount, amountOf(height, l, r));
23+
if (height[l] < height[r]) {
24+
l++;
25+
} else if (height[l] > height[r]) {
26+
r--;
27+
} else {
28+
int nextLeftAmount = amountOf(height, l+1, r);
29+
int nextRightAmount = amountOf(height, l, r-1);
30+
if (nextLeftAmount < nextRightAmount) {
31+
r--;
32+
} else {
33+
l++;
34+
}
35+
}
36+
}
37+
38+
return maxAmount;
39+
}
40+
41+
private int amountOf(int[] height, int left, int right) {
42+
return (Math.min(height[left], height[right]) * (right - left));
43+
}
44+
}
45+

0 commit comments

Comments
 (0)