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;
typedef long long int ll;
typedef long double ld;
#define rep(i,a,b)  for(ll i=a;i<b;i++)
#define nl cout<<endl
 
#define pii pair<ll,ll>
#define vi  vector<ll>
#define vii vector<pii>
#define mi  map<ll,ll>
#define all(a)  (a).begin(),(a).end()

#define pb push_back
#define ff first
#define ss second
#define mod 1000000007

#define yes cout<<"Yes"<<endl;
#define no cout<<"No"<<endl;
#define test4(x,y,z,a) cout<<"x is "<<x<<"		y is "<<y<<"		z is "<<z<<"		a is "<<a<<endl;
#define test3(x,y,z) cout<<"x is "<<x<<"		y is "<<y<<"		z is "<<z<<endl;
#define test2(x,y) cout<<"x is "<<x<<"		y is "<<y<<endl;
#define test1(x) cout<<"x is "<<x<<endl;

int main(){
	ios_base::sync_with_stdio(false);
     	cin.tie(NULL);
    	cout.tie(NULL);    
    ll n,k;cin>>n>>k;
    ll ar[k];
    rep(i,0,n){
        cin>>ar[i];
    }
    ll total=0;
    ll s=0;
    rep(i,1,k){
        if(total< ar[i]-ar[i-1] ){
           s=i;
           total= ar[i]-ar[i-1];
        }
    }
    if(ar[0]==0){
        if(total< n-ar[k-1]){
            s=1;
            total= n-ar[k-1];
        }
    }else{
        if(total< n-ar[k-1]+ar[0]){
            s=1;
            total= n-ar[k-1]+ar[0];
        }
    }
    ll h=0;
    rep(i,1,k){
        h+= ar[i]-ar[i-1];
    }
    // ll ans=0;
    // for(i,0,k){
        
    // }
//     ll ans=0;
//     rep(i,s,k-1){
//         ans+= ar[i+1]-ar[i];
//     }
//     ans+= n-ar[k-1];
//   // test1(ans);
//     rep(i,0,s-1){
//         ans+= ar[i+1]-ar[i];
//     }
    //cout<<total<<" "<<s<<" "<<ans<<endl;
    cout<<min(h , n-total)<<endl;
    
    return 0;
}