A-013● Day 132026.05.15mediumleetcode #11neetcode150
Container With Most Water
#array#two-pointers#greedy
01
Problem
· problemYou are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container.
constraints
- · n == height.length
- · 2 ≤ n ≤ 10^5
- · 0 ≤ height[i] ≤ 10^4
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐How is the area of water calculated between two lines?
- ☐Can we use any two lines with different indices?
- ☐Why should we move the pointer pointing to the smaller height?
- ☐What if two adjacent lines have the same height?
- ☐Must we check all possible pairs of lines?
- ☐Can the container be oriented vertically instead of horizontally?
- ☐Do we need to modify the original height array?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Initialize pointers at opposite ends
○
l, r = 0, len(height) - 1
○
l, r = 0, len(height) // 2
○
l, r = 1, len(height) - 2
step 2· Initialize maximum area tracker
○
res = 0
○
res = float('-inf')○
res = height[0] * (len(height) - 1)
step 3· Loop while pointers haven't crossed
○
while l < r:
○
while l <= r:
○
while r - l > 1:
step 4· Calculate area and track maximum│ nested
○
res = max(res, min(height[l], height[r]) * (r - l))
○
res = max(res, height[l] * height[r] * (r - l))
○
res = max(res, (height[l] + height[r]) * (r - l))
step 5· Move pointer at smaller height│ nested
○
if height[l] < height[r]:
○
if height[l] > height[r]:
○
if l < r // 2:
step 6· Move left pointer inward│ │ nested
○
l += 1
○
l -= 1
○
l += 2
step 7· Move right pointer inward (when applicable)│ │ nested
○
r -= 1
○
r += 1
○
r -= 2
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[1,8,6,2,5,4,8,3,7]→
49
case 2
[1,1]→
1
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.