problems / 166

Container With Most Water

medium two-pointers greedy arrays 1000 ms · 256 MB

Container With Most Water

There are n vertical lines standing on the x-axis. Line i (1-indexed) stands at x = i and has height h_i.

Choose two different lines i < j. Together with the x-axis they form a container; the water it holds can rise only up to the shorter of the two lines, so its area is

min(h_i, h_j) · (j − i).

The lines between i and j do not get in the way. Find the largest area any pair of lines can hold.

Input

The first line contains an integer n (2 ≤ n ≤ 10^6), the number of lines.

The second line contains n integers h_1, h_2, …, h_n (0 ≤ h_i ≤ 10^9).

Output

Print one integer: the maximum of min(h_i, h_j) · (j − i) over all pairs 1 ≤ i < j ≤ n.

Notes

In the first example, lines 2 and 9 have heights 8 and 7, so the container holds min(8, 7) · (9 − 2) = 49. No other pair does better.

In the second example, every pair contains a line of height 0 except lines 2 and 3, which hold 5 · 1 = 5.

The answer can be as large as about 10^15, so it does not fit in a 32-bit integer.

Example 1

Input

9
1 8 6 2 5 4 8 3 7

Output

49

Example 2

Input

4
0 5 5 0

Output

5

Hints · reveal one at a time if you're stuck

Hint 1

Start with the widest possible pair of lines. If one of the two lines is the shorter one, can it still be part of a better pair with some line strictly inside the current range?

Hint 2

Use two pointers from both ends and always move the pointer at the shorter line inward, recording the best area seen. Compute the area in 64-bit integers.

report an issue Prefer your own editor? sooks prep 166 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.