use proconio::{fastout, input};
use std::iter::repeat;

#[fastout]
fn main() {
    input! {
        n: i32,
        a_i: [i32; n],
    }

    let mut h: Vec<i32> = repeat(0).take(a_i.len()).collect();

    for (i, val) in a_i.iter().enumerate() {
        if i == 0 {
            continue;
        }

        let prev_index = i - 1;
        let prev = a_i[prev_index];
        let prev_h = h[prev_index];

        if prev + prev_h > *val {
            h[i] = prev + prev_h - val;
        }
    }

    println!("{}", h.iter().sum::<i32>());
}
