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>
#include<cstdio>

#define deb(x) cout << #x << " -> " << x << el 
#define db double
#define ll long long int
#define ld long double
#define ull unsigned long long int
#define sc(x) scanf("%d", &x)
#define scl(x) scanf("%lld", &x)
#define sclu(x) scanf("%llu", &x)
#define scd(x) scanf("%lf", &x)
#define scld(x) scanf("%Lf", &x)
#define pass cout<<"pass\n"
#define vi vector<int>
#define eb emplace_back
#define pb push_back
#define vec vector
#define el "\n"
#define pii pair<int, int>
#define F first
#define S second
#define mp make_pair
#define mt make_tuple
#define f(i,x,y) for(int i=x;i<y;++i)
#define ff(i,x,y) for(int i=x;i<=y;++i)
#define mem(x) memset(x, 0, sizeof(x))
#define mems(x,y) memset(x, y, sizeof(x))
#define MOD 1000000007
#define MAX 200005

using namespace std;

int n, p;
int ar[MAX];

void solve() {
	cin >> p >> n;
	f(i,0,n) {
		cin >> ar[i];
	}
	int mn = -1e9;
	ll sum = 0LL;
	for(int i = 1; i < n; ++i) {
		sum += 1LL * (ar[i] - ar[i - 1]);
		mn = max(mn, ar[i] - ar[i - 1]);
	}
	// deb(sum);
	// deb(mn);
	sum += 1LL * p + ar[0] - ar[n - 1];
	mn = max(mn, p + ar[0] - ar[n - 1]);
	// deb(sum);
	// deb(mn);
	cout << sum - mn << el;
}


int main() {
	// clock_t start = clock();
	// freopen("./input.in", "r", stdin);
	int tt = 1;
	// sc(tt);
	while(tt--) {
		solve();
	}
	// clock_t finish = clock();
	// printf("Time taken: %0.9lf sec\n", (double)((finish - start) / CLOCKS_PER_SEC));
 	
	return 0;
}