tryhardyoninfinityhz

Untitled

Feb 25th, 2022
1,188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. // By Dhruv Kothari
  2. import java.util.*;
  3. public class p3v2{
  4.     public static void main(String[] args) {
  5.         Scanner scan = new Scanner (System.in);
  6.         int t=scan.nextInt();
  7.         while (t>0) {
  8.            int n=scan.nextInt();
  9.            long a[] = new long  [n+1];
  10.            for (int i=0; i<n; i++)
  11.                 a[i]=scan.nextInt();
  12.            long ans=0;
  13.                    if (n==1) {System.out.println(ans); t--; continue;}
  14.                    if (n==2 && a[0]==a[1]) {System.out.println(ans); t--; continue;}
  15.                    if (n==2 && a[0]!=a[1]) {System.out.println("-1"); t--; continue;}
  16.  
  17.            for (int i=0; i<n-1; i++)
  18.                if (a[i+1]>a[i])  {
  19.                    long dif=a[i+1]-a[i];
  20.                    ans+=2*dif;
  21.                    a[i+1]-=dif;
  22.                    a[i+2]-=dif;
  23.                }
  24.                if (a[n]<0 || a[n-1]<0) ans=-1;
  25.                else {
  26.                    for (int i=n-1; i>1; i--)
  27.                       if (a[i-1]>a[i]) {
  28.                           long dif=a[i-1]-a[i];
  29.                           a[i-2]-=dif;
  30.                           a[i-1]-=dif;
  31.                           ans+=2*dif;
  32.                       }
  33.                       if (a[0]!=a[1] || a[0]!=a[2] || a[0]<0) ans=-1;
  34.                    
  35.                }
  36. for (int i=0; i<n; i++)  if (a[i]<0) ans=-1;
  37.  
  38.  
  39.             System.out.println(ans);
  40.            t--;
  41.         }
  42.        
  43.    
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment