All problems

Problem 315

Maximum Weighted Sum over Rotations

Medium · 20 pts · Array, Math, Prefix Sum

Problem

For an array B of length N, define its weighted sum as 0·B[0] + 1·B[1] + ... + (N-1)·B[N-1]. Consider every rotation of the given array A (rotating left by 0, 1, ..., N-1 positions) and print the largest weighted sum among them. An O(N²) solution recomputes each sum; an O(N) solution updates the sum from one rotation to the next.

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 weighted sum over all rotations.

Constraints

1 <= N <= 100000; -100000 <= A[i] <= 100000 (the answer fits in a 64-bit integer)

Example input

4
8 3 1 2

Example output

29

Explanation

For 8 3 1 2, the rotation 3 1 2 8 has weighted sum 0·3 + 1·1 + 2·2 + 3·8 = 29, which is larger than for any other rotation.

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

Previous: Chocolate Distribution Next: Segregate Even and Odd Numbers