2026/04/26

[LeetCode] 11 Container With Most Water

Two Pointer

容量大小是由小的那邊決定

每次收縮小的那邊

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
public:
  int maxArea(vector<int>& height) {
    int left = 0;
    int right = height.size() - 1;
    int ans = 0;

    while (left < right) {
      int cur = (right - left) * min(height[left], height[right]);
      ans = max(ans, cur);
      if (height[left] < height[right])
        left++;
      else
        right--;
    }
    return ans;
  }
};