简繁EN

LeetCodeNo. 090

[LeetCode with Python] 11. Container With Most Water

Contents

Problem

Problem page: https://leetcode.com/problems/container-with-most-water/
Topics: Array, Two Pointers
Difficulty: Medium
Similar problems: (H) Trapping Rain Water

Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.


Analysis

The greedy idea is to start two pointers at opposite ends of the array and search inward. There are two reasons for this:

  1. The base is already as wide as it can be at the start. It only gets narrower as the pointers move inward. So the area can only grow if the smaller of the two heights is greater than it was before the move. Otherwise, there's no need to check the area. Just continue to the next iteration.
  2. So when choosing whether to move the left or right pointer, move the one at the shorter side in the hope of finding a taller side. Moving the pointer at the taller side could skip the optimal solution.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
# @return an integer
def maxArea(self, height):
len_height = len(height)
if 1 == len_height:
return 0
max_area = 0
left_index = 0
right_index = len_height - 1
while left_index < right_index:
if height[left_index] < height[right_index]:
area = (right_index - left_index) * height[left_index]
left_index += 1
else:
area = (right_index - left_index) * height[right_index]
right_index -= 1
if area > max_area:
max_area = area
return max_area

Article link: https://xnerv.wang/en/leetcode-container-with-most-water/