Biggest Tank Between Two Posts

Medium · Two Pointers · about 20 min

A farmer has a row of wooden posts, 1 metre apart. posts[i] is the height of post i. She stretches a sheet between two posts to make a water tank. The water between posts i and j (with i < j) is

min(posts[i], posts[j]) * (j - i)

(the posts in between do not matter). Return the largest amount of water any two posts can hold. With fewer than two posts, return 0.

Example:

best_tank_volume([1, 8, 6, 2, 5, 4, 8, 3, 7]) → 49 (posts 1 and 8: min(8, 7) * 7)

Aim for O(n) time.

Hints

  • Start with the widest tank: the first and the last post.
  • The water level is set by the shorter post. Would moving the taller one inward ever help?
  • Always move the shorter post inward and keep the best amount seen.

Learn the pattern first: the Two Pointers lesson.

More Two Pointers problems