Skip to content

Commit e037d9e

Browse files
author
Jeongwon Na
committed
solution: container with most water
1 parent ba08f52 commit e037d9e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Time Complexity: O(n), n: height.length
2+
// Space Complexity: O(1)
3+
class Solution {
4+
public int maxArea(int[] height) {
5+
int maxWaterAmount = 0;
6+
int leftLineIdx = 0;
7+
int rightLineIdx = height.length-1;
8+
9+
while (leftLineIdx < rightLineIdx) {
10+
int leftHeight = height[leftLineIdx];
11+
int rightHeight = height[rightLineIdx];
12+
int tempAmount = 0;
13+
14+
if (leftHeight < rightHeight) {
15+
tempAmount = leftHeight * (rightLineIdx - leftLineIdx);
16+
leftLineIdx++;
17+
} else {
18+
tempAmount = rightHeight * (rightLineIdx - leftLineIdx);
19+
rightLineIdx--;
20+
}
21+
22+
// update maximum amount
23+
maxWaterAmount = tempAmount > maxWaterAmount ? tempAmount : maxWaterAmount;
24+
}
25+
26+
return maxWaterAmount;
27+
}
28+
}

0 commit comments

Comments
 (0)