unittest
{
	assert( [ "4", "0", "1", "1", "2" ].parse.expand.solve == 3 );
	assert( [ "3", "1", "2", "1" ].parse.expand.solve == -1 );
	assert( [ "9", "0", "1", "1", "0", "1", "2", "2", "1", "2" ].parse.expand.solve == 8 );
}



import std.conv;
import std.range;
import std.stdio;
import std.typecons;

void main()
{
	stdin.byLineCopy.parse.expand.solve.writeln;
}

auto parse( Range )( Range input )
if( isInputRange!Range && is( ElementType!Range == string ) )
{
	auto n = input.front.to!( long );
	auto as = new long[ n ];
	foreach( ref a; as )
	{
		input.popFront;
		a = input.front.to!( long );
	}
	return tuple( as );
}

auto solve( long[] as )
{
	auto ans = 0L;
	auto m = 0L;
	foreach_reverse( i, a; as )
	{
		if( i < a || a < m ) return -1;
		if( m < a ) ans += a;
		m = a - 1;
	}
	return ans;
}
