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:
- 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.
- 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 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-container-with-most-water/
