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)

macro_rules ! input { ( source = $ s : expr , $ ( $ r : tt ) * ) => { let mut iter = $ s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; ( iter = $ iter : ident , $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut $ iter = s . split_whitespace ( ) ; input_inner ! { $ iter , $ ( $ r ) * } } ; ( $ ( $ r : tt ) * ) => { let s = { use std :: io :: Read ; let mut s = String :: new ( ) ; std :: io :: stdin ( ) . read_to_string ( & mut s ) . unwrap ( ) ; s } ; let mut iter = s . split_whitespace ( ) ; input_inner ! { iter , $ ( $ r ) * } } ; }
macro_rules ! input_inner { ( $ iter : expr ) => { } ; ( $ iter : expr , ) => { } ; ( $ iter : expr , mut $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let mut $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , mut $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , mut $ var : usize $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident : $ t : tt $ ( $ r : tt ) * ) => { let $ var = read_value ! ( $ iter , $ t ) ; input_inner ! { $ iter $ ( $ r ) * } } ; ( $ iter : expr , $ var : ident $ ( $ r : tt ) * ) => { input_inner ! { $ iter , $ var : usize $ ( $ r ) * } } ; }
macro_rules ! read_value { ( $ iter : expr , ( $ ( $ t : tt ) ,* ) ) => { ( $ ( read_value ! ( $ iter , $ t ) ) ,* ) } ; ( $ iter : expr , [ $ t : tt ; $ len : expr ] ) => { ( 0 ..$ len ) . map ( | _ | read_value ! ( $ iter , $ t ) ) . collect ::< Vec < _ >> ( ) } ; ( $ iter : expr , { chars : $ base : expr } ) => { read_value ! ( $ iter , String ) . chars ( ) . map ( | c | ( c as u8 - $ base as u8 ) as usize ) . collect ::< Vec < usize >> ( ) } ; ( $ iter : expr , { char : $ base : expr } ) => { read_value ! ( $ iter , { chars : $ base } ) [ 0 ] } ; ( $ iter : expr , chars ) => { read_value ! ( $ iter , String ) . chars ( ) . collect ::< Vec < char >> ( ) } ; ( $ iter : expr , char ) => { read_value ! ( $ iter , chars ) [ 0 ] } ; ( $ iter : expr , usize1 ) => { read_value ! ( $ iter , usize ) - 1 } ; ( $ iter : expr , $ t : ty ) => { $ iter . next ( ) . unwrap ( ) . parse ::<$ t > ( ) . unwrap ( ) } ; }
pub trait Monoid {
    type T: Clone + PartialEq;
    fn mempty(&self) -> Self::T;
    fn mappend(&self, x: &Self::T, y: &Self::T) -> Self::T;
}
#[doc = " RMaxQ & RUpdQ M1=max F1=M2=subs"]
#[doc = " RMinQ & RAddQ M1=min F1=M2=add"]
#[doc = " RSumQ & RAddQ M1=F1=M2=add                  F2=a*b"]
#[doc = " RSumQ & RUpdQ M1=add F1=M2=subs             F2=a*b"]
#[doc = " RSumQ & RXorQ M1=add F1=(b>=1?b-a:a) M2=a^b F2=a*b"]
#[derive(Clone, Debug)]
pub struct LazySegmentTree<
    M1: Monoid,
    M2: Monoid,
    F1: Fn(&M1::T, &M2::T) -> M1::T,
    F2: Fn(&M2::T, usize) -> M2::T,
> {
    n: usize,
    seg: Vec<M1::T>,
    lazy: Vec<M2::T>,
    m1: M1,
    m2: M2,
    op: F1,
    p: F2,
}
impl<M1: Monoid, M2: Monoid, F1: Fn(&M1::T, &M2::T) -> M1::T, F2: Fn(&M2::T, usize) -> M2::T>
    LazySegmentTree<M1, M2, F1, F2>
{
    pub fn new(n: usize, m1: M1, m2: M2, op: F1, p: F2) -> LazySegmentTree<M1, M2, F1, F2> {
        let n = 1 << format!("{:b}", n - 1).len();
        let seg = vec![m1.mempty(); 2 * n - 1];
        let lazy = vec![m2.mempty(); 2 * n - 1];
        LazySegmentTree {
            n: n,
            seg: seg,
            lazy: lazy,
            m1: m1,
            m2: m2,
            op: op,
            p: p,
        }
    }
    pub fn from_vec(
        v: Vec<M1::T>,
        m1: M1,
        m2: M2,
        op: F1,
        p: F2,
    ) -> LazySegmentTree<M1, M2, F1, F2> {
        let n = 1 << format!("{:b}", v.len() - 1).len();
        let mut seg = vec![m1.mempty(); 2 * n - 1];
        for (i, x) in v.into_iter().enumerate() {
            seg[i + n - 1] = x;
        }
        for i in (0..n - 1).rev() {
            seg[i] = m1.mappend(&seg[2 * i + 1], &seg[2 * i + 2]);
        }
        let lazy = vec![m2.mempty(); 2 * n - 1];
        LazySegmentTree {
            n: n,
            seg: seg,
            lazy: lazy,
            m1: m1,
            m2: m2,
            op: op,
            p: p,
        }
    }
    pub fn eval(&mut self, k: usize, len: usize) {
        if self.lazy[k] != self.m2.mempty() {
            if k * 2 + 1 < self.n * 2 - 1 {
                self.lazy[2 * k + 1] = self.m2.mappend(&self.lazy[2 * k + 1], &self.lazy[k]);
                self.lazy[2 * k + 2] = self.m2.mappend(&self.lazy[2 * k + 2], &self.lazy[k]);
            }
            self.seg[k] = (self.op)(&self.seg[k], &(self.p)(&self.lazy[k], len));
            self.lazy[k] = self.m2.mempty();
        }
    }
    fn update_inner(
        &mut self,
        l: usize,
        r: usize,
        x: M2::T,
        k: usize,
        a: usize,
        b: usize,
    ) -> M1::T {
        self.eval(k, b - a);
        if b <= l || r <= a {
            self.seg[k].clone()
        } else if l <= a && b <= r {
            self.lazy[k] = self.m2.mappend(&self.lazy[k], &x);
            (self.op)(&self.seg[k], &(self.p)(&self.lazy[k], b - a))
        } else {
            let lx = self.update_inner(l, r, x.clone(), k * 2 + 1, a, (a + b) / 2);
            let rx = self.update_inner(l, r, x, k * 2 + 2, (a + b) / 2, b);
            let res = self.m1.mappend(&lx, &rx);
            self.seg[k] = res.clone();
            res
        }
    }
    pub fn update(&mut self, l: usize, r: usize, x: M2::T) -> M1::T {
        let n = self.n;
        self.update_inner(l, r, x, 0, 0, n)
    }
    fn query_inner(&mut self, l: usize, r: usize, k: usize, a: usize, b: usize) -> M1::T {
        self.eval(k, b - a);
        if b <= l || r <= a {
            self.m1.mempty()
        } else if l <= a && b <= r {
            self.seg[k].clone()
        } else {
            let lx = self.query_inner(l, r, k * 2 + 1, a, (a + b) / 2);
            let rx = self.query_inner(l, r, k * 2 + 2, (a + b) / 2, b);
            self.m1.mappend(&lx, &rx)
        }
    }
    pub fn query(&mut self, l: usize, r: usize) -> M1::T {
        let n = self.n;
        self.query_inner(l, r, 0, 0, n)
    }
}
#[derive(Clone, Debug)]
pub struct AnyMonoid<T: Clone, F: Fn(&T, &T) -> T> {
    id: T,
    op: F,
}
impl<T: Clone, F: Fn(&T, &T) -> T> AnyMonoid<T, F> {
    pub fn new(id: T, op: F) -> AnyMonoid<T, F> {
        AnyMonoid { id: id, op: op }
    }
}
impl<T: Clone + PartialEq, F: Fn(&T, &T) -> T> Monoid for AnyMonoid<T, F> {
    type T = T;
    fn mempty(&self) -> T {
        self.id.clone()
    }
    fn mappend(&self, x: &T, y: &T) -> T {
        (self.op)(x, y)
    }
}
fn main() {
    input! { n, m, a: [usize1; n] };
    let mut seg = LazySegmentTree::new(
        m * 2,
        AnyMonoid::new(0i64, |&x, &y| x + y),
        AnyMonoid::new(0i64, |&x, &y| x + y),
        |&x, &y| x + y,
        |&x, y| x * y as i64,
    );
    let mut d = 0;
    for i in 0..n - 1 {
        let (l, r) = if a[i] < a[i + 1] {
            (a[i], a[i + 1])
        } else {
            (a[i], a[i + 1] + m)
        };
        d += r - l;
        seg.update(l + 2, r + 1, 1);
        seg.update(r + 1, r + 2, l as i64 - r as i64 + 1);
    }
    let mut ans = d as i64;
    for i in 0..m {
        let x = seg.query(0, i + 1) + seg.query(0, i + m + 1);
        ans = std::cmp::min(ans, d as i64 - x);
    }
    println!("{}", ans);
}