Problem:
Score : 200 points

Problem Statement

There are K pieces of cakes.
Mr. Takahashi would like to eat one cake per day, taking K days to eat them all.

There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i.

Eating the same type of cake two days in a row would be no fun,
so Mr. Takahashi would like to decide the order for eating cakes that minimizes the number of days on which he has to eat the same type of cake as the day before.

Compute the minimum number of days on which the same type of cake as the previous day will be eaten.

Constraints

1 ≤ K ≤ 10000

1 ≤ T ≤ 100

1 ≤ a_i ≤ 100

a_1 + a_2 + ... + a_T = K

Input

The input is given from Standard Input in the following format:

K T
a_1 a_2 ... a_T

Output

Print the minimum number of days on which the same type of cake as the previous day will be eaten.

Sample Input 1

7 3
3 2 2

Sample Output 1

0

For example, if Mr. Takahashi eats cakes in the order of 2, 1, 2, 3, 1, 3, 1, he can avoid eating the same type of cake as the previous day.

Sample Input 2

6 3
1 4 1

Sample Output 2

1

There are 6 cakes.
For example, if Mr. Takahashi eats cakes in the order of 2, 3, 2, 2, 1, 2, he has to eat the same type of cake (i.e., type 2) as the previous day only on the fourth day.
Since this is the minimum number, the answer is 1.

Sample Input 3

100 1
100

Sample Output 3

99

Since Mr. Takahashi has only one type of cake, he has no choice but to eat the same type of cake as the previous day from the second day and after.

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

use std::io::Read;
use std::collections::BinaryHeap;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).unwrap();

    let answer = solve(&buf);

    println!("{}", answer);
}

fn solve(input: &str) -> String {
    let mut iterator = input.split_whitespace();

    let k: usize = iterator.next().unwrap().parse().unwrap();
    let t: usize = iterator.next().unwrap().parse().unwrap();
    let mut pq: BinaryHeap<(usize, usize)> = BinaryHeap::new();
    for i in 1..(t + 1) {
        let a: usize = iterator.next().unwrap().parse().unwrap();
        pq.push((a, i));
    }

    let mut ans: usize = 0;
    let mut prev: usize = 0;
    for _ in 0..k {
        let mut first = pq.pop().unwrap();
        if first.1 != prev {
            prev = first.1;
            first.0 -= 1;
            if first.0 > 0 {
                pq.push(first);
            }
        } else {
            if let Some(mut second) = pq.pop() {
                prev = second.1;
                second.0 -= 1;
                if second.0 > 0 {
                    pq.push(second);
                }
                pq.push(first);
            } else {
                prev = first.1;
                first.0 -= 1;
                if first.0 > 0 {
                    pq.push(first);
                }
                ans += 1;
            }
        }
    }
    return format!("{}", ans);
}