CF BUDDY
← Problems·

1903C · Theofanis' Nightmare

1400 · constructive algorithms, greedy

Problem: 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 aa of size nn and wants to divide it into non-empty subarrays^{\dagger} such that every element is in exactly one of the subarrays.

For example, the array [1,3,7,6,2,5][1,-3,7,-6,2,5] can be divided to [1][3,7][6,2][5][1] [-3,7] [-6,2] [5].

The Cypriot value of such division is equal to Σi=1kisumi\Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i where kk is the number of subarrays that we divided the array into and sumi\mathrm{sum}_i is the sum of the ii-th subarray.

The Cypriot value of this division of the array [1][3,7][6,2][5]=11+2(3+7)+3(6+2)+45=17[1] [-3,7] [-6,2] [5] = 1 \cdot 1 + 2 \cdot (-3 + 7) + 3 \cdot (-6 + 2) + 4 \cdot 5 = 17.

Theofanis is wondering what is the maximum Cypriot value of any division of the array.

^{\dagger} An array bb is a subarray of an array aa if bb can be obtained from aa 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 Format: The first line contains a single integer tt (1t1041 \le t \le 10^4) — the number of test cases.

Each test case consists of two lines.

The first line of each test case contains a single integer nn (1n1051 \le n \le 10^{5}) — the size of the array.

The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (108ai108-10^8 \le a_i \le 10^{8}) — the elements of the array.

It is guaranteed that the sum of nn over all test cases does not exceed 21052 \cdot 10^{5}.

Output Format: For each test case, print one integer — the maximum Cypriot value of the array aa.

Note: In the first test case, to get the maximum Cypriot value we divide the array into [1][3][7][6][2][5][1][-3][7][-6][2][5] which gives us: Σi=1kisumi=11+2(3)+37+4(6)+52+65=32\Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i = 1 \cdot 1 + 2 \cdot (-3) + 3 \cdot 7 + 4 \cdot (-6) + 5 \cdot 2 + 6 \cdot 5 = 32

Similarly, in the second test case we divide the array into [2][9,5,3][2][9,-5,-3] which gives us Σi=1kisumi=12+2(9+(5)+(3))=4\Sigma_{i=1}^{k} i \cdot \mathrm{sum}_i = 1 \cdot 2 + 2 \cdot (9 + (-5) + (-3)) = 4.

Sample Cases

Case 1

Input

4
6
1 -3 7 -6 2 5
4
2 9 -5 -3
8
-3 -4 2 -5 1 10 17 23
1
830

Output

32
4
343
830

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback