function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}
function Main(input) {
  input = myconv(input,5);
  var N = input[0];
  input.shift();
  if(input[0] != 0){
     myout(-1);
    return;
  }
  var output = 0;
  if(input[N-1] != 0){
     output++;
  }
  for(var i = N-1; i >= 1; i--){
    var mae = input[i-1];
    var ato = input[i];
    if(ato - mae > 1){
       myout(-1);
      return;
    }
    if(mae == 0){
       continue;
    }
    if(mae == 1 && ato == 1){
       output++;
       continue;
    }
    if(ato - mae == 1){
       output++;
    }else{
      if(ato >= 2){
        output += 2; 
      }else{
      	output ++;
      }
    }
  }
  myout(output);
}
Main(myin());