Backdrop Between Poles

Mediumtwo pointersAlso known as Container With Most Water

A photographer sets up in a park where a row of wooden poles stands exactly 1 metre apart. The poles have different heights. She wants to stretch one rectangular backdrop between two of the poles.

The backdrop is as wide as the distance between the two poles, and it can only be as tall as the shorter of the two, or it would sag. The poles in between do not get in the way: the backdrop hangs in front of them. Which two poles give 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, so the area is 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 two tall neighbours, 10 and 9, give 1 × 9 = 9. Wider pairs are all held down by a short pole: 2 and 9 give 2 × 2 = 4, and 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 compute its area. Keep the largest.

With 10,000 poles there are about 50 million pairs. Most of them are hopeless: a pair whose short pole has already been paired with something farther away can never win, and the 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