function Main(input) {
	input = input.split("\n");
	var n = input[0];
	var arry = input.slice(1,n+1);
	var ret = 0;
	
	for(var i = 0; i < n; i++){
		if(i == 0 && arry[i] != 0 || arry[i] - arry[i-1] > 1){
			console.log(-1);
			return;
		}
		
		if(arry[i] == arry[i-1]){
			ret += Number(arry[i]);
		} else if (arry[i] != 0){
			ret++;
		}
	}
	console.log(ret);
	
	return ;
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));