Theofanis easily gets obsessed with problems before going to sleep and often has…
- User
Theofanis easily gets obsessed with problems before going to sleep and often has nightmares about them. To deal with his obsession he visited his doctor, Dr. Emix.
In his latest nightmare, he has an array 𝑎 of size 𝑛 and wants to divide it into non-empty subarrays† such that every element is in exactly one of the subarrays.
For example, the array [1,−3,7,−6,2,5] can be divided to [1][−3,7][−6,2][5] .
The Cypriot value of such division is equal to Σ𝑘𝑖=1𝑖⋅sum𝑖 where 𝑘 is the number of subarrays that we divided the array into and sum𝑖 is the sum of the 𝑖 -th subarray.
The Cypriot value of this division of the array [1][−3,7][−6,2][5]=1⋅1+2⋅(−3+7)+3⋅(−6+2)+4⋅5=17 .
Theofanis is wondering what is the maximum Cypriot value of any division of the array.
† An array 𝑏 is a subarray of an array 𝑎 if 𝑏 can be obtained from 𝑎 by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. In particular, an array is a subarray of itself.
Input The first line contains a single integer 𝑡 (1≤𝑡≤104 ) — the number of test cases.
Each test case consists of two lines.
The first line of each test case contains a single integer 𝑛 (1≤𝑛≤105 ) — the size of the array.
The second line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (−108≤𝑎𝑖≤108 ) — the elements of the array.
It is guaranteed that the sum of 𝑛 over all test cases does not exceed 2⋅105 .
Output For each test case, print one integer — the maximum Cypriot value of the array 𝑎 .
Example inputCopy 4 6 1 -3 7 -6 2 5 4 2 9 -5 -3 8 -3 -4 2 -5 1 10 17 23 1 830 outputCopy 32 4 343 830 Note In the first test case, to get the maximum Cypriot value we divide the array into [1][−3][7][−6][2][5] which gives us: Σ𝑘𝑖=1𝑖⋅sum𝑖=1⋅1+2⋅(−3)+3⋅7+4⋅(−6)+5⋅2+6⋅5=32 Similarly, in the second test case we divide the array into [2][9,−5,−3] which gives us Σ𝑘𝑖=1𝑖⋅sum𝑖=1⋅2+2⋅(9+(−5)+(−3))=4 .
- Assistant
To find the maximum Cypriot value of the array, we can use dynamic programming approach. Let's define a new array dp[], where dp[i] represents the maximum Cypriot value obtainable for the subarray ending at index i.
For each index i, we can either start a new subarray with element a[i] or add element a[i] to the previous subarray. We need to find the choice that gives us the maximum Cypriot value.
To determine the maximum Cypriot value, we have the following choices:
-
Start a new subarray: In this case, dp[i] = a[i].
-
Extend the previous subarray: In this case, we need to consider all the previous subarrays ending at index j (0 ≤ j < i). We can calculate the sum of the subarray from index j+1 to i, and add it to the Cypriot value of the subarray ending at index j. The Cypriot value of the subarray ending at index j is dp[j]. Therefore, dp[i] = dp[j] + (i - j) * sum(j+1 to i).
-