Under construction

Still being built. Things may change

Jump

Time limit2sMemory limit1024 MB

Summary
Given building heights, sum the minimum total squared-height-difference cost over all pairs of buildings that can reach each other by visible jumps, modulo 1000000007.
Level

Hard9 of 10

Topics
Tree, Divide and conquer, Dynamic programming
Solved
No attempts yet

Problem

A road runs left and right, and NN buildings stand along it. The buildings are numbered from 11 to NN from left to right in the order they were built, and building ii has height HiH_i.

Chaewan, who has outstanding physical ability, can jump between the rooftops of two different buildings aa and bb that satisfy the following condition.

  • Every building between building aa and building bb has height less than min⁡(Ha,Hb)\min(H_a, H_b).

Each jump costs stamina equal to the square of the difference between the two building heights. How far apart the two buildings are to the left or right does not affect the stamina cost.

Let D(a,b)D(a, b) be the minimum total stamina needed for Chaewan to move from the rooftop of building aa to the rooftop of building bb using jumps only. Find ∑i=1N−1∑j=i+1ND(i,j)\sum_{i=1}^{N-1} \sum_{j=i+1}^{N} D(i, j).

Input

The first line contains the number of buildings NN. (2≤N≤500 000)(2 \le N \le 500\,000)

The second line contains the heights H1,H2,⋯ ,HNH_1, H_2, \cdots, H_N, separated by spaces. All heights are integers and are distinct. (1≤Hi≤109)(1 \le H_i \le 10^9)

Output

Print the remainder of ∑i=1N−1∑j=i+1ND(i,j)\sum_{i=1}^{N-1} \sum_{j=i+1}^{N} D(i, j) divided by 1 000 000 0071\,000\,000\,007.

Examples1

  1. Example 1

    Input
    5
    3 10 4 7 6
    
    Expected output
    290