N = gets.to_i B = gets.split.map(&:to_i) stock = [] empty = [] ans = 0 B.each_with_index do |b, idx| if b == 0 if stock.empty? empty << idx else i, cnt = stock.pop ans += idx - i cnt -= 1 stock.push([i, cnt]) if cnt > 0 end else while empty.size > 0 && b > 0 i = empty.pop ans += idx - i b -= 1 end if b == 0 empty.push(idx) elsif b >= 2 stock.push([idx, b - 1]) end end end puts ans