All problems

Problem 826

Maximum Subarray Min-Product

Medium · 20 pts · Array, Monotonic Stack, Prefix Sum

Problem

The min-product of a block of consecutive elements is its minimum multiplied by its sum. Find the largest min-product over all non-empty blocks, and print it modulo 1000000007 (take the remainder only after finding the maximum). For every element, find how far the block can extend while that element stays the minimum, using a monotonic stack for the nearest smaller elements on both sides, and prefix sums for the block sum. Keep the counts in a 64-bit integer type (long long in C++, long in Java) and take the remainder after every addition and multiplication: adding or multiplying two remainders can be larger than a 32-bit int can hold (Python needs nothing special).

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].

Output

Print the maximum min-product modulo 1000000007.

Constraints

1 <= N <= 100000; 1 <= A[i] <= 10^7

Example input

4
1 2 3 2

Example output

14

Explanation

In 1 2 3 2, the block 2 3 2 has minimum 2 and sum 7, so its min-product is 14. No other block does better, so the answer is 14.

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

Previous: Element Appearing More Than 25% in a Sorted Array Next: Range Sum of Sorted Subarray Sums