Problem:
Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

2 \leq N \leq 2 \times 10^5

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.

Solution in C++14 (Clang 3.8.0) (judge verdict: Accepted)

//#define _XCODE_DEBUG

#include <iostream>
#include <vector>

#ifdef _XCODE_DEBUG
    #include <fstream>
#endif

int main(int argc, const char * argv[]) {
    #ifdef _XCODE_DEBUG
        std::ifstream in("input.txt");
        std::cin.rdbuf(in.rdbuf());
    #endif
    
    int K, N;
    int a;
    std::cin >> K >> N;
    std::vector<int> vec_a;
    
    for(int i=0; i<N; ++i) {
        std::cin >> a;
        vec_a.push_back(a);
    }
    
    int ans = vec_a[N-1] - vec_a[0];
    for (int i=1; i<N; ++i) {
        int dist1 = vec_a[N-1] - vec_a[i];
        int dist2 = (K-vec_a[N-1]) + vec_a[i];
        int dist = dist1 + dist2;
        if (ans > dist) ans = dist;
    }
    for (int i=N-2; i>0; --i) {
        int dist1 = vec_a[i];
        int dist2 = std::abs(K-vec_a[i+1]);
        int dist = dist1 + dist2;
        if (ans > dist) ans = dist;
    }
    std::cout << ans << "\n";
    return 0;
}