Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // By Dhruv Kothari
- import java.util.*;
- public class p3v2{
- public static void main(String[] args) {
- Scanner scan = new Scanner (System.in);
- int t=scan.nextInt();
- while (t>0) {
- int n=scan.nextInt();
- long a[] = new long [n+1];
- for (int i=0; i<n; i++)
- a[i]=scan.nextInt();
- long ans=0;
- if (n==1) {System.out.println(ans); t--; continue;}
- if (n==2 && a[0]==a[1]) {System.out.println(ans); t--; continue;}
- if (n==2 && a[0]!=a[1]) {System.out.println("-1"); t--; continue;}
- for (int i=0; i<n-1; i++)
- if (a[i+1]>a[i]) {
- long dif=a[i+1]-a[i];
- ans+=2*dif;
- a[i+1]-=dif;
- a[i+2]-=dif;
- }
- if (a[n]<0 || a[n-1]<0) ans=-1;
- else {
- for (int i=n-1; i>1; i--)
- if (a[i-1]>a[i]) {
- long dif=a[i-1]-a[i];
- a[i-2]-=dif;
- a[i-1]-=dif;
- ans+=2*dif;
- }
- if (a[0]!=a[1] || a[0]!=a[2] || a[0]<0) ans=-1;
- }
- for (int i=0; i<n; i++) if (a[i]<0) ans=-1;
- System.out.println(ans);
- t--;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment