#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
    int data;
    struct Node*next;
}Node;
void push(Node**top,int value){
    Node*newNode=(Node*)malloc(sizeof(Node));
    newNode->data=value;
    newNode->next=*top;
    *top=newNode;
} 
int main(){
    int K;
    if (scanf("%d",&K) !=1) {
        printf("Invalid input\n");
        return 0;
    }
    if (K < 5|| K > 12) {
        printf("Invalid input\n");
        return 0;
    }
    int arr[K];
    for (inti=0;i<k;i++){
        if(scanf("%d",&arr[i])!=1 ||arr[i]<1||
        arr[i]>1000) {
            printf("Invalid input\n");
            return 0;
            
        }
    }
    Node*stack = NULL) {
        for (int i=1;i<k;i++){
            if (arr[i]<arr[i-1]) {
                push(&stack,arr[i]);
                
            }
        }
        if(stack==NULL) {
        printf("-1\n");
        return 0;
    }
    int total=0;
    NOde*temp=stack;
    while(temp !=NULL) {
        total+=temp->data;
        temp=temp->next
    }
printf("%d\n",total);
return 0;
}