Problem:
Score : 300 points

Problem Statement

In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0.
You are given a sequence h=\{h_1,h_2,h_3,......\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation:

Specify integers l and r. Increase the height of Flower x by 1 for all x such that l \leq x \leq r.

Find the minimum number of watering operations required to satisfy the condition.

Constraints

1 \leq N \leq 100

0 \leq h_i \leq 100

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
h_1 h_2 h_3 ...... h_N

Output

Print the minimum number of watering operations required to satisfy the condition.

Sample Input 1

4
1 2 2 1

Sample Output 1

2

The minimum number of watering operations required is 2.
One way to achieve it is:

Perform the operation with (l,r)=(1,3).

Perform the operation with (l,r)=(2,4).

Sample Input 2

5
3 1 2 3 1

Sample Output 2

5

Sample Input 3

8
4 23 75 0 23 96 50 100

Sample Output 3

221

Solution in Rust (1.15.1) (judge verdict: Accepted)


use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
  let stdin = stdin();
  let stdin = stdin.lock();
  let token: String = stdin
    .bytes()
    .map(|c| c.expect("failed to read char") as char)
    .skip_while(|c| c.is_whitespace())
    .take_while(|c| !c.is_whitespace())
    .collect();
  token.parse().ok().expect("failed to parse token")
}

fn main() {
  let n = read::<i32>();
  let mut a = vec![];

  for _ in 0..n {
    let a_i = read::<i32>();
    a.push(a_i);
  }

  let base = a.iter().min().expect("faild to find min");

  println!("{}", dsf(&a[..], base) + base);
}

fn dsf(a_p: &[i32], base: &i32) -> i32 {
  let a_min = match a_p.iter().min() {
    Some(s) => s,
    None => return 0,
  };
  let min_idx = find_all(a_p, *a_min);

  if min_idx.len() == a_p.len() {
    return a_min - base;
  }

  let mut prev_i: usize = 0;
  let mut sum = 0;

  for i in &min_idx {
    let a_slice = &a_p[prev_i..*i];
    sum += dsf(a_slice, a_min);

    prev_i = i + 1;
  }

  if prev_i < a_p.len() {
    let a_slice = &a_p[prev_i..];
    sum += dsf(a_slice, a_min);
  }
  sum += (*a_min - base);
  sum
}

fn find_all(a_p: &[i32], t: i32) -> Vec<usize> {
  let mut a_is = vec![];
  for (i, v) in a_p.iter().enumerate() {
    if *v == t {
      a_is.push(i);
    }
  }
  return a_is;
}