-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer-with-most-water.ts
More file actions
36 lines (33 loc) · 1.05 KB
/
Copy pathcontainer-with-most-water.ts
File metadata and controls
36 lines (33 loc) · 1.05 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
/**
* 11. Container With Most Water (Medium)
* Link: https://leetcode.com/problems/container-with-most-water/
*
* `height[i]` is the height of a vertical line at position i. Pick two lines
* that, with the x-axis, form a container holding the most water. Return that
* maximum area.
*
* Example:
* Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
* Output: 49
*
* Approach:
* Two pointers at the widest possible span. Area is width * min(left, right).
* Moving the taller wall inward can only shrink both width and height, so we
* always advance the shorter wall — the only move that might find a taller
* line and beat the current best.
*
* Time: O(n) — pointers meet in one pass.
* Space: O(1)
*/
export function maxArea(height: number[]): number {
let left = 0;
let right = height.length - 1;
let best = 0;
while (left < right) {
const area = (right - left) * Math.min(height[left], height[right]);
if (area > best) best = area;
if (height[left] < height[right]) left++;
else right--;
}
return best;
}