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 (GCC 5.4.1) (judge verdict: Accepted)

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ss second
#define ff first
#define pb push_back
#define pll pair<long long, long long>
#define FIO ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);

ll dx[] = {1,-1,0,0};
ll dy[] = {0,0,1,-1};
const ll sz = 3e5+5,mod = 998244353;
ll t,n,m,k;
vector<ll> p(sz),sp(sz),fac(sz);

const ll lim = 1e18;
const ll inf = 1e15;

ll Power(ll a, ll b)
{
    if(a==0)
        return 0;
    if(b==0)
        return 1;
    ll ans=Power((a*a)%mod,b/2);
    if(b&1)
        return (a*ans)%mod;
    return ans%mod;
}
ll Inv(ll a)
{
    return Power(a,mod-2);
}


int main()
{
    FIO
    ll Max = 0;
    cin>>n>>m;
    vector<ll> v(m);
    for(int i=0;i<m;i++)
        cin>>v[i];
    sort(v.begin(),v.end());
    for(int i=0;i<m;i++)
    {
        ll j = (i+1)%m;
        ll tmp = 0;
        if(v[j] < v[i])
           tmp += v[j]+n-v[i];
        else
            tmp += v[j]-v[i];

        Max = max(Max,tmp);
    }
    cout<<n-Max;

}