fn main(){
    let mut buf = String::new();
    std::io::stdin().read_line(&mut buf).expect("failed to read");
    buf.clear();

    std::io::stdin().read_line(&mut buf).expect("failed to read");
    let va: Vec<u32> = buf.split_whitespace().map(|e| e.parse().unwrap()).collect();
    
    let (tc, _): (u32, u32) = va.iter().fold((0, 0), |(tc, mh), &a| if mh <= a {(tc, a)} else {(tc + mh - a, mh)});
        
    println!("{}", tc)
}
