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 r = b - 1 if r <= 0 empty.push(idx) else stock.push([idx, r]) end end end puts ans