Problem:
Score : 700 points

Problem Statement

Snuke is buying a lamp.
The light of the lamp can be adjusted to m levels of brightness, represented by integers from 1 through m, by the two buttons on the remote control.

The first button is a "forward" button. When this button is pressed, the brightness level is increased by 1, except when the brightness level is m, in which case the brightness level becomes 1.

The second button is a "favorite" button. When this button is pressed, the brightness level becomes the favorite brightness level x, which is set when the lamp is purchased.

Snuke is thinking of setting the favorite brightness level x so that he can efficiently adjust the brightness.
He is planning to change the brightness n-1 times. In the i-th change, the brightness level is changed from a_i to a_{i+1}. The initial brightness level is a_1.
Find the number of times Snuke needs to press the buttons when x is set to minimize this number.

Constraints

2 \leq n,m \leq 10^5

1 \leq a_i\leq m

a_i \neq a_{i+1}

n, m and a_i are integers.

Input

Input is given from Standard Input in the following format:

n m
a_1 a_2 … a_n

Output

Print the minimum number of times Snuke needs to press the buttons.

Sample Input 1

4 6
1 5 1 4

Sample Output 1

5

When the favorite brightness level is set to 1, 2, 3, 4, 5 and 6, Snuke needs to press the buttons 8, 9, 7, 5, 6 and 9 times, respectively.
Thus, Snuke should set the favorite brightness level to 4.
In this case, the brightness is adjusted as follows:

In the first change, press the favorite button once, then press the forward button once.

In the second change, press the forward button twice.

In the third change, press the favorite button once.

Sample Input 2

10 10
10 9 8 7 6 5 4 3 2 1

Sample Output 2

45

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

// use std::ops::{Index, IndexMut};
// use std::cmp::{Ordering, min, max};
// use std::collections::{BinaryHeap, BTreeMap};
// use std::collections::btree_map::Entry::{Occupied, Vacant};
// use std::clone::Clone;

fn getline() -> String{
    let mut res = String::new();
    std::io::stdin().read_line(&mut res).ok();
    res
}

macro_rules! readl {
    ($t: ty) => {
        {
            let s = getline();
            s.trim().parse::<$t>().unwrap()
        }
    };
    ($( $t: ty),+ ) => {
        {
            let s = getline();
            let mut iter = s.trim().split(' ');
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*) 
        }
    };
}

macro_rules! readlvec {
    ($t: ty) => {
        {
            let s = getline();
            let iter = s.trim().split(' ');
            iter.map(|x| x.parse().unwrap()).collect::<Vec<$t>>()
        }
    }
}

macro_rules! debug {
    ($x: expr) => {
        println!("{}: {:?}", stringify!($x), $x)
    }
}

fn printiter<'a, T>(v: &'a T)
where
    &'a T: std::iter::IntoIterator, 
    <&'a T as std::iter::IntoIterator>::Item: std::fmt::Display {
    for (i,e) in v.into_iter().enumerate() {
        if i != 0 {
            print!(" ");
        }
        print!("{}", e);
    }
    println!("");
}

struct ContestPrinter {
    s: String,
}

impl ContestPrinter {
    fn new() -> ContestPrinter {
        ContestPrinter {
            s: String::new(),
        }
    }

    fn print<T>(&mut self, x: T)
        where T: std::fmt::Display {
        self.s.push_str(format!("{}", x).as_str());
    }

    fn println<T>(&mut self, x: T)
        where T: std::fmt::Display {
        self.s.push_str(format!("{}\n", x).as_str());
    }
}

impl std::ops::Drop for ContestPrinter {
    fn drop(&mut self) {
        print!("{}", self.s);
    }
}

fn naive(n: usize, m: usize, a: &Vec<i64>) {
    let dist = |x, y| if x <= y {
        y-x
    } else {
        m as i64 +y-x
    };
    for k in 0..m {
        let mut ans = 0;
        for i in 0..n-1 {
            ans += std::cmp::min(dist(a[i], a[i+1]), 1+dist(k as i64, a[i+1]));
            // debug!(a[i+1]); debug!(a[i]); debug!(k); debug!(dist(a[i+1], a[i])); debug!(dist(k as i64, a[i+1]));
            // debug!(std::cmp::min(dist(a[i], a[i+1]), 1+dist(k as i64, a[i+1])));
        }
        println!("{}", ans);
    }
}

fn main() {
    let mut printer = ContestPrinter::new();
    let(n, m) = readl!(usize, usize);
    let a: Vec<_> = readlvec!(i64).into_iter().map(|x| x-1).collect();
    let mut imos = vec![0; m+1];
    let mut end = vec![Vec::new(); m+1];
    // imos[1] += 1;
    // imos[a[0] as usize+1] -= 1;
    // end[a[0] as usize+1].push(a[0]);
    // debug!(a);
    let mut val = 0;
    for i in 0..n-1 {
        // debug!(i);
        // debug!(imos);
        // debug!(end);
        let d = a[i+1]-a[i];
        // debug!(d);
        if d == 0 {
            continue;
        }
        if d < 0 {
            // let t = std::cmp::min(m as i64+d, a[i+1]+1);
            val += std::cmp::min(m as i64+d, a[i+1]+1);
            imos[0] += 1;
            imos[a[i+1] as usize+1] -= 1;
            end[a[i+1] as usize+1].push(m as i64+d);
            imos[a[i] as usize+1] += 1;
            imos[m] -= 1;
            end[m].push(m as i64+d);
        } else {
            // let t = std::cmp::min(d, a[i+1]*1); 
            val += std::cmp::min(d, a[i+1]*1);
            imos[a[i] as usize+1] += 1;
            imos[a[i+1] as usize+1] -= 1;
            end[a[i+1] as usize+1].push(d);
        }
        // debug!(val);
    }
    // debug!(imos);
    // debug!(end);
    let mut ans = val;
    // debug!(ans);
    let mut co = imos[0];
    for i in 1..m {
        for &e in &end[i] {
            val += e;
        }
        val -= co;
        // debug!(val);
        ans = std::cmp::min(ans, val);
        co += imos[i];
    }
    printer.println(ans);
    // naive(n, m, &a);
}