HTML & JS
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define l long long 

int main() 
{
    int t; cin >> t;
    while(t--)
    {
        l n; cin >> n;
        l a[n];
        for(int i=0;i<n;i++)
        {
            cin >> a[i];
        }
        l max_till=a[0],val=LLONG_MAX,flag=0,ans=0;
        for(int i=0;i<n;i++)
        {
            if(a[i]>=max_till)
            {
                if(flag==1)
                {
                    ans=ans+(max_till-val);
                    val=LLONG_MAX;
                    flag=0;
                }
                max_till=a[i]; 
            }
            if(a[i]<max_till)
            {
                flag=1;
                val=min(val,a[i]);
            }
        }
        if(flag==1)
        {
            ans=ans+(max_till-val);;
        }
        cout << ans << endl;
    }
}
 

Generated URL:

Output:

3
2
0
Report Bug