Source Code
#include <bits/stdc++.h>

#define ll long long

#define fast ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);

using namespace std;

const ll N = 2e5 + 7;

ll t, n, ans;

pair<ll, ll> p[N];

int main()
{
    fast
    cin >> t;
    while(t--)
    {
        cin >> n;
        for(int i = 0; i < n; i++)
        {
            cin >> p[i].first;
            p[i].second = i + 1;
        }
        sort(p, p + n);
        ll mx = p[0].second, mn = p[0].second;
        ans = n;
        for(int i = 1; i < n; i++)
        {
            ll x = p[i].second;
            if(x <= mx && x >= mn) continue;
            else if(x > mx) ans += mn * (x - mx) * p[i].first;
            else ans += (mn - x) * (n + 1 - mx) * p[i].first;
            mx = max(mx, x);
            mn = min(mn, x);
        }
        cout << ans << endl;
    }
}
Copy
Mex Mohamad_Abodan
GNU G++17
51 ms
3.5 MB
Accepted