Back to lesson

examples/10.py

Code and original product screens keep their original language. The lesson explains them in your selected language.

# Before: the loop variable is unused and the stopping rule is buried.
def max_area_before(li):
    l, best, r = 0, 0, len(li) - 1
    for _ in li:
        best = max(best, min(li[l], li[r]) * (r - l))
        if li[r] < li[l]:
            r -= 1
        else:
            l += 1
        if l >= r:
            break
    return best

# After: the same supported results with explicit pointer names and loop bounds.
def max_water_area(heights):
    left, right = 0, len(heights) - 1
    best = 0
    while left < right:
        width = right - left
        height = min(heights[left], heights[right])
        best = max(best, width * height)
        # Keeping the shorter boundary cannot improve the area.
        if heights[left] <= heights[right]:
            left += 1
        else:
            right -= 1
    return best

assert max_water_area([1,8,6,2,5,4,8,3,7]) == 49
assert max_water_area([]) == 0
for heights in ([], [5], [1,8,6,2,5,4,8,3,7]):
    assert max_area_before(heights) == max_water_area(heights)