All problems

Problem 812

Sum of All Odd Length Subarrays

Easy · 10 pts · Array, Math, Prefix Sum

Problem

Add up the sums of all blocks of consecutive elements that have an odd length (1, 3, 5, ...). Blocks at different positions count separately. Instead of enumerating the blocks, count how many odd-length blocks contain each element: element i is in (i + 1) × (N - i) blocks in total, and ceil of half of them have odd length. Multiply each element by that count and add everything up.

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 total of all odd-length subarray sums.

Constraints

1 <= N <= 100000; 1 <= A[i] <= 1000

Example input

5
1 4 2 5 3

Example output

58

Explanation

For 1 4 2 5 3, the length-1 blocks sum to 15, the length-3 blocks (1 4 2, 4 2 5, 2 5 3) sum to 7 + 11 + 10 = 28, and the whole array sums to 15. The total is 58.

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

Previous: Valid Mountain Array Next: Find the Highest Altitude