All problems

Problem 30

Container With Most Water

Medium · 20 pts · Array, Two Pointers, Greedy

Problem

You are given N vertical lines standing on the x-axis. Line i is at position i and has height H[i]. Choose two lines that, together with the x-axis, form a container, and find the largest amount of water such a container can hold. The water level is limited by the shorter of the two lines, and the width is the distance between them, so lines i < j hold (j - i) × min(H[i], H[j]) units of water. A two-pointer approach works in O(N): start with the widest pair (first and last line) and repeatedly move the pointer at the shorter line inward, because keeping the shorter line can never lead to a bigger container.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the maximum amount of water.

Constraints

2 <= N <= 100000; 0 <= H[i] <= 10000

Example input

9
1 8 6 2 5 4 8 3 7

Example output

49

Explanation

In 1 8 6 2 5 4 8 3 7, the lines at index 1 (height 8) and index 8 (height 7) are 7 apart. The water level is min(8, 7) = 7, so they hold 7 × 7 = 49 units, the largest possible.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Best Time to Buy and Sell Stock II Next: Trapping Rain Water