Skip to content

Commit 954ec01

Browse files
committed
feat : container-with-most-water
1 parent bd19c48 commit 954ec01

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
input : array of integer height
3+
output : maximum amount of water a container can store.
4+
5+
we can build container with two different line (height[i], height[j] when i < j)
6+
7+
example
8+
1 8 6 2 5 4 8 3 7
9+
choose i = 1.
10+
choose j = 4
11+
8 ______5
12+
amount of water == (j - i) * min(height[i], height[j])
13+
= 3 * 5 = 15
14+
15+
we have to maximize amount of water.
16+
17+
constraints:
18+
1) is the input array valid?
19+
length of array is in range [2, 10^5]
20+
2) positive integers?
21+
no. range of height is [0, 10 ^4]
22+
>> check amount can be overflow. 10^4 * 10 ^ 5 = 10^9 < Integer range
23+
edge:
24+
1) if length is 2
25+
return min(height[0], height[1]).
26+
...
27+
28+
solution 1) brute force;
29+
iterate through the array from index i = 0 to n-1
30+
when n is the length of input array
31+
iterate through the array from index j = i + 1 to n;
32+
calculate the amount of water and update max amount
33+
ds : array
34+
algo : x
35+
tc : O(n^2) ~= 10^10 TLE
36+
space : O(1)
37+
38+
solution 2) better
39+
ds : array
40+
algo: two pointer?
41+
42+
two variant for calculating amount of water
43+
1. height 2. width
44+
45+
set width maximum at first, check heights
46+
decrease width one by one
47+
48+
- at each step width is maximum.
49+
so we have to maximize
50+
the minimum between left and right pointer
51+
52+
use left and right pointer
53+
while left < right
54+
55+
calculate amount
56+
compare
57+
if height[left] < height[right]
58+
move left by one
59+
else
60+
vice versa
61+
62+
return max
63+
tc : O(n)
64+
sc : O(1)
65+
66+
*/
67+
class Solution {
68+
public int maxArea(int[] height) {
69+
int left = 0;
70+
int right = height.length - 1;
71+
int maxAmount = 0;
72+
while(left < right) {
73+
int curAmount = (right - left) * Math.min(height[left], height[right]);
74+
maxAmount = Math.max(maxAmount, curAmount);
75+
if(height[left] < height[right]) {
76+
left++;
77+
} else {
78+
right--;
79+
}
80+
}
81+
return maxAmount;
82+
}
83+
}

0 commit comments

Comments
 (0)