Backdrop Between Poles

Mediumtwo pointersAlso known as Container With Most Water

A photographer works in a park with a row of wooden poles of different heights, exactly 1 metre apart. She wants to stretch one rectangular backdrop between two of them.

The backdrop is as wide as the gap between the poles and only as tall as the shorter one, or it sags. Poles in between do not matter, because the backdrop hangs in front of them. She wants the pair of poles that gives the biggest backdrop.

Your task

Write widestBackdrop(heights). heights[i] is the height of pole i. For two poles i < j, the backdrop area is (j - i) × min(heights[i], heights[j]). Return the largest possible area.

If there are fewer than two poles, return 0.

widestBackdrop(heights: int[]) → int

Examples

Example 1
Input
heights = [3, 7, 2, 6, 4, 8, 1]
Output
28
Why

Poles 1 (height 7) and 5 (height 8) are 4 metres apart, and the shorter is 7: 4 × 7 = 28. The two ends give only 6 × 1 = 6, because pole 6 is so short.

Example 2
Input
heights = [2, 10, 9, 1]
Output
9
Why

The tall neighbours 10 and 9 give 1 × 9 = 9. Wider pairs are held down by a short pole: 2 and 9 give 2 × 2 = 4, 2 and 1 give 3 × 1 = 3.

Constraints

  • 0 ≤ heights.length ≤ 10,000
  • 0 ≤ heights[i] ≤ 10,000
Start with brute force

Try every pair of poles and keep the largest area.

With 10,000 poles that is about 50 million pairs. Most are hopeless: a pair whose short pole was already paired with something farther away can never win, yet brute force checks it anyway.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code