const log = console.log;

const parseLines = (s: string) => s.trim().split("\n");
const parseSpaceSeparated = (line: string) => line.trim().split(" ");
const parseDecimalInt = (s: string) => parseInt(s);
const parseSpaceSeparatedDecimalInt = (line: string) =>
  parseSpaceSeparated(line).map(parseDecimalInt);

const ascendingSorter = (a: number, b: number) => a - b;

const accumulateLimited = (numArray: number[], limit: number) => {
  let sum = 0;
  let count = 0;

  for (const currentNum of numArray) {
    const nextSum = sum + currentNum;
    if (nextSum > limit) break;
    sum = nextSum;
    count += 1;
  }

  return { amount: sum, count };
};

// ----

function Main(input: string): void {
  const [head, body] = parseLines(input);
  const [n, x] = parseSpaceSeparatedDecimalInt(head);
  const a = parseSpaceSeparatedDecimalInt(body);

  a.sort(ascendingSorter);

  const maxSum = accumulateLimited(a, x);
  let satisfiedCount = maxSum.count;

  // last child not satisfied
  if (satisfiedCount === a.length && maxSum.amount < x) satisfiedCount -= 1;

  log(satisfiedCount);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const log = console.log;

const parseLines = (s: string) => s.trim().split("\n");
const parseSpaceSeparated = (line: string) => line.trim().split(" ");

const parseDecimalInt = (s: string) => parseInt(s);

const parseSpaceSeparatedDecimalInt = (line: string) =>
  parseSpaceSeparated(line).map(parseDecimalInt);

const ascendingSorter = (a: number, b: number) => a - b;

const getMaxSum = (numArray: number[], limit: number) => {
  let sum = 0;
  let count = 0;

  for (const currentNum of numArray) {
    const nextSum = sum + currentNum;
    if (nextSum > limit) break;
    sum = nextSum;
    count += 1;
  }

  return { amount: sum, count };
};

// ----

function Main(input: string): void {
  const [head, body] = parseLines(input);
  const [n, x] = parseSpaceSeparatedDecimalInt(head);
  const a = parseSpaceSeparatedDecimalInt(body);

  a.sort(ascendingSorter);

  const maxSum = getMaxSum(a, x);
  let childCount = maxSum.count;
  if (childCount > 0 && maxSum.amount < x) childCount -= 1; // last child not satisfied

  log(childCount);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const log = console.log;

const parseLines = (s: string) => s.trim().split("\n");
const parseSpaceSeparated = (line: string) => line.trim().split(" ");

const parseDecimalInt = (s: string) => parseInt(s);

const parseSpaceSeparatedDecimalInt = (line: string) =>
  parseSpaceSeparated(line).map(parseDecimalInt);

const ascendingSorter = (a: number, b: number) => a - b;

const getMaxSum = (array: number[], limit: number) => {
  let sum = 0;
  let count = 0;

  for (const currentNum of array) {
    const nextSum = sum + currentNum;
    if (nextSum > limit) break;
    sum = nextSum;
    count += 1;
  }

  return { amount: sum, count };
};

// ----

function Main(input: string): void {
  const [head, body] = parseLines(input);
  const [n, x] = parseSpaceSeparatedDecimalInt(head);
  const a = parseSpaceSeparatedDecimalInt(body);

  a.sort(ascendingSorter);

  const maxSum = getMaxSum(a, x);
  const childCount = maxSum.amount === x ? maxSum.count : maxSum.count - 1;

  log(childCount);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const log = console.log;

const parseLines = (s: string) => s.trim().split("\n");
const parseSpaceSeparated = (line: string) => line.trim().split(" ");

const parseDecimalInt = (s: string) => parseInt(s);

const parseSpaceSeparatedDecimalInt = (line: string) =>
  parseSpaceSeparated(line).map(parseDecimalInt);

const ascendingSorter = (a: number, b: number) => a - b;

const getMaxSum = (array: number[], limit: number) => {
  let sum = 0;
  let count = 0;

  for (const currentNum of array) {
    const nextSum = sum + currentNum;
    if (nextSum > limit) break;
    sum = nextSum;
    count += 1;
  }

  return { sum, count };
};

// ----

function Main(input: string): void {
  const [head, body] = parseLines(input);
  const [n, x] = parseSpaceSeparatedDecimalInt(head);
  const a = parseSpaceSeparatedDecimalInt(body);

  a.sort(ascendingSorter);

  log(getMaxSum(a, x).count);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


import sys

def main():
    read = sys.stdin.buffer.read
    k, n, *A = map(int, read().split())
    far = k + A[0] - A[-1]
    y = A[0]
    for x in A[1:]:
        dis = x - y
        if far < dis:
            far = dis
        y = x
    print(k - far)

if __name__ == "__main__":
    main()


import sys

read = sys.stdin.buffer.read
K,N,*A = map(int, read().split())
A += [A[0]+K]
gap = max(y-x for x,y in zip(A, A[1:]))

print(K-gap)


import sys
read = sys.stdin.buffer.read

K, N, *A = map(int, read().split())
A.append(A[0] + K)
gap = max(y - x for x, y in zip(A, A[1:]))
print(K - gap)


k,n=map(int,input().split())
a=[int(X ) for X in input().split()]
x=[0]*(n+1)
for i in range(1,n+1):
    x[i]=a[i-1]-a[i-2]
x[0]=min(a[-1]-a[0],k-a[-1]+a[0] )
print(max(x))


K, N = map(int, input().split())
A = sorted(map(int, input().split()))
assert len(A) == N

dists = []
for i,start in enumerate(A):
  # 右回り
  posR = A[(i - 1) % N] + K
  #max([a + K for a in A[:i]] + A[i+1:])
  # 左回り
  posL = A[(i + 1) % N] - K
  #posL = min(A[:i] + [a - K for a in A[i+1:]])
  dists.append(min(posR - start, - posL + start))
print(min(dists))


K, N = map(int, input().split())
A = sorted(map(int, input().split()))
assert len(A) == N

dists = []
for i,start in enumerate(A):
  # 右回り
  posR = max([a + K for a in A[:i]] + A[i+1:])
  # 左回り
  posL = min(A[:i] + [a - K for a in A[i+1:]])
  dists.append(min(posR - start, - posL + start))
print(min(dists))


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;

/**
 * @author khokharnikunj8
 */

public class Main {
    public static void main(String[] args) {
        new Thread(null, new Runnable() {
            public void run() {
                new Main().solve();
            }
        }, "1", 1 << 26).start();
    }

    void solve() {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        ScanReader in = new ScanReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        CTravelingSalesmanAroundLake solver = new CTravelingSalesmanAroundLake();
        solver.solve(1, in, out);
        out.close();
    }

    static class CTravelingSalesmanAroundLake {
        public void solve(int testNumber, ScanReader in, PrintWriter out) {
            int k = in.scanInt();
            int n = in.scanInt();
            int[] ar = new int[n];
            for (int i = 0; i < n; i++) ar[i] = in.scanInt();
            int ans = Integer.MAX_VALUE;
            for (int i = 0; i < n - 1; i++) {
                ans = Math.min(ans, ar[i] + (k - ar[i + 1]));
            }
            ans = Math.min(ans, ar[n - 1] - ar[0]);
            out.println(ans);
        }

    }

    static class ScanReader {
        private byte[] buf = new byte[4 * 1024];
        private int index;
        private BufferedInputStream in;
        private int total;

        public ScanReader(InputStream inputStream) {
            in = new BufferedInputStream(inputStream);
        }

        private int scan() {
            if (index >= total) {
                index = 0;
                try {
                    total = in.read(buf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (total <= 0) return -1;
            }
            return buf[index++];
        }

        public int scanInt() {
            int integer = 0;
            int n = scan();
            while (isWhiteSpace(n)) n = scan();
            int neg = 1;
            if (n == '-') {
                neg = -1;
                n = scan();
            }
            while (!isWhiteSpace(n)) {
                if (n >= '0' && n <= '9') {
                    integer *= 10;
                    integer += n - '0';
                    n = scan();
                }
            }
            return neg * integer;
        }

        private boolean isWhiteSpace(int n) {
            if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
            else return false;
        }

    }
}


import java.io.*;
import java.io.IOException;
import java.util.*;
//import javafx.util.Pair;
//import java.util.concurrent.LinkedBlockingDeque;

//import sun.net.www.content.audio.wav;

import java.text.DecimalFormat;

public class Main {

    public static long mod = (long)Math.pow(10, 9)+7 ;
    public static double epsilon=0.00000000008854;//value of epsilon
    public static InputReader sc = new InputReader(System.in);
    public static PrintWriter pw = new PrintWriter(System.out);

    public static void diji(PriorityQueue<Pair> q,ArrayList<ArrayList<Pair>> a){
        //int vis[]=new int[a.size()];
        boolean vis[]=new boolean[a.size()];
        //vis[0]=1;
        Arrays.fill(vis, false);
        int n=a.size();
        long val[]=new long[n];

        long inf=Long.MAX_VALUE;
        Arrays.fill(val, inf);
        q.add(new Pair(0, 0));
        val[0]=0;
        int p[]=new int[n];
        p[0]=-1;
        while(q.size()>0){
            Pair r=q.remove();
            if(vis[r.i])
            continue;
            vis[r.i]=true;///removed
            int u=r.i;
            for(int i=0;i<a.get(u).size();i++){

                int v=a.get(u).get(i).i;
                long w=a.get(u).get(i).j;
                    if(val[v]>r.j+w){
                        p[v]=u;
                        val[v]=r.j+w;
                        q.add(new Pair(v, val[v]));
                    }
            }
        }
        //pw.println(Arrays.toString(p));
        int i=n-1;
        Stack<Integer> st=new Stack<>();
        if(val[i]==inf)
        {
            pw.println(-1);
            return;
        }
        while(i!=-1){
            st.add(i+1);
            i=p[i];
        }
        while(st.size()>0){
            pw.print(st.pop()+" ");
        }

    }
    public static int countSet(int a){
        int c=0;
        while(a>0){
            a&=(a-1);
            c++;
        }
        return c;
    }
    public static void Zfunction(String s){
        int n=s.length();
        int a[]=new int[n];
        int r1=0,r2=1;
        for(int i=1;i<n;){
            int f=0;
            while(r2<n&&s.charAt(r1)==s.charAt(r2)){
                r1++;
                r2++;
            }
            a[i]=r1;
            i++;
            int l2=1;
            for(;i<r2;i++){
                if(i+a[l2]<r2)
                a[i]=a[l2++];
                else{
                    f=1;
                    r1=r2-i;
                    break;
                }
            }
            if(f==0){
                r2=i;
                r1=0;
            }

        }
        pw.println(Arrays.toString(a));
    }
    public static void main(String[] args) {
        // code starts..

      int k=sc.nextInt();
      int n=sc.nextInt();
      int a[]=scanArray(n);
      int diff=a[0];
      for(int i=1;i<=n;i++){
          int a1=a[i%n]-a[i-1];
          if(a1<0){
              a1+=k;
          }
        diff=Math.max(a1, diff);
      }

      pw.println(k-diff);

        // Code ends...
        pw.flush();
        pw.close();
    }
    public static Comparator<Integer> C(){
        return
        new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2.compareTo(o1);//for descending
            }
        };
    }
    public static Comparator<Pair> di(){
        return
        new Comparator<Pair>() {
            @Override
            public int compare(Pair o1, Pair o2) {
                Long a=o1.j;
                Long b=o2.j;
                return a.compareTo(b);//ascending
            }
        };
    }
    static class tripletL implements Comparable<tripletL> {
        Long x, y, z;

        tripletL(long x, long y, long z) {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public int compareTo(tripletL o) {
            int result = x.compareTo(o.x);
            if (result == 0)
                result = y.compareTo(o.y);
            if (result == 0)
                result = z.compareTo(o.z);

            return result;
        }

        public boolean equlas(Object o) {
            if (o instanceof tripletL) {
                tripletL p = (tripletL) o;
                return (x - p.x == 0) && (y - p.y ==0 ) && (z - p.z == 0);
            }
            return false;
        }

        public String toString() {
            return x + " " + y + " " + z;
        }

        public int hashCode() {
            return new Long(x).hashCode() * 31 + new Long(y).hashCode() + new Long(z).hashCode();
        }
    }
    public static String Doubleformate(double a,int n){
        String s="";
        while(n-->0){
            s+='0';
        }
        DecimalFormat f =new DecimalFormat("#0."+s);
        return f.format(a);
    }

    public static Comparator<Integer[]> column(int i){
        return
        new Comparator<Integer[]>() {
            @Override
            public int compare(Integer[] o1, Integer[] o2) {
                return o1[i].compareTo(o2[i]);//for ascending
                //return o2[i].compareTo(o1[i]);//for descending
            }
        };
    }
    public static Comparator<Integer[]> pair(){
        return
        new Comparator<Integer[]>() {
            @Override
            public int compare(Integer[] o1, Integer[] o2) {
                int result=o1[0].compareTo(o2[0]);
                if(result==0)
                result=o1[1].compareTo(o2[1]);
                return result;
            }
        };
    }
    public static Comparator<Integer[]> Triplet(){
        return
        new Comparator<Integer[]>() {
            @Override
            public int compare(Integer[] o1, Integer[] o2) {

                    for(int i=0;i<3;i++){
                        for(int j=i+1;j<3;j++){
                            for(int k=0;k<3;k++){
                                for(int p=k+1;p<3;p++){
                                    if((o1[i]==o2[k]&&o1[j]==o2[p])||(o1[j]==o2[k]&&o1[i]==o2[p])){

                                    }
                                }
                            }
                        }
                    }
                    int result=o1[0].compareTo(o2[0]);
                    if(result==0)
                    result=o1[1].compareTo(o2[1]);
                    if(result==0)
                    result=o1[2].compareTo(o2[2]);
                    return result;
            }
        };
    }

    public static String reverseString(String s){
        StringBuilder input1 = new StringBuilder();
        input1.append(s);
        input1 = input1.reverse();
        return input1.toString();
    }
    public static int[] scanArray(int n){
        int a[]=new int [n];
        for(int i=0;i<n;i++)
        a[i]=sc.nextInt();

        return a;
    }
    public static long[] scanLongArray(int n){
        long a[]=new long [n];
        for(int i=0;i<n;i++)
        a[i]=sc.nextLong();

        return a;
    }
    public static String [] scanStrings(int n){
        String a[]=new String [n];
        for(int i=0;i<n;i++)
        a[i]=sc.nextLine();

        return a;
    }

}
class Pair{
    int i;
    long j;
    Pair(int a,long b){
        i=a;
        j=b;
    }
}
class InputReader {

        private final InputStream stream;
        private final byte[] buf = new byte[8192];
        private int curChar, snumChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int snext() {
            if (snumChars == -1)
                throw new InputMismatchException();
            if (curChar >= snumChars) {
                curChar = 0;
                try {
                    snumChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (snumChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public long nextLong() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = snext();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = snext();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public int[] nextIntArray(int n) {
            int a[] = new int[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextInt();
            }
            return a;
        }

        public String readString() {
            int c = snext();
            while (isSpaceChar(c)) {
                c = snext();
            }
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public String nextLine() {
            int c = snext();
            while (isSpaceChar(c))
                c = snext();
            StringBuilder res = new StringBuilder();
            do {
                res.appendCodePoint(c);
                c = snext();
            } while (!isEndOfLine(c));
            return res.toString();
        }

        public boolean isSpaceChar(int c) {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        private boolean isEndOfLine(int c) {
            return c == '\n' || c == '\r' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);
        }
    }


import java.io.*;
import java.util.*;

class Main {
    public static void main(String[] args) throws IOException {
        Scan sc = new Scan();
        int k = sc.scanInt();
        int n = sc.scanInt();
        int[] dists = new int[n];
        int max = 0;
        int prev = 0;
        for(int i = 0; i < n; ++i){
            int curr = sc.scanInt();
            if(i == n-1)
                dists[0] = k-(curr-dists[0]);
            if(i > 0){
                dists[i] = curr - prev;
            }
            else
                dists[i] = curr;
            max = Math.max(max, dists[i]);
            prev = curr;
        }
        max = Math.max(max, dists[0]);
        System.out.println(k-max);
    }
}

class Scan
{
    private byte[] buf=new byte[1024];
    private int index;
    private InputStream in;
    private int total;
    public Scan()
    {
        in=System.in;
    }
    public int scan()throws IOException
    {
        if(total<0)
        throw new InputMismatchException();
        if(index>=total)
        {
            index=0;
            total=in.read(buf);
            if(total<=0)
            return -1;
        }
        return buf[index++];
    }
    public int scanInt()throws IOException
    {
        int integer=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n))
        {
            if(n>='0'&&n<='9')
            {
                integer*=10;
                integer+=n-'0';
                n=scan();
            }
            else throw new InputMismatchException();
        }
        return neg*integer;
    }
    public double scanDouble()throws IOException
    {
        double doub=0;
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        int neg=1;
        if(n=='-')
        {
            neg=-1;
            n=scan();
        }
        while(!isWhiteSpace(n)&&n!='.')
        {
            if(n>='0'&&n<='9')
            {
                doub*=10;
                doub+=n-'0';
                n=scan();
            }
            else throw new InputMismatchException();
        }
        if(n=='.')
        {
            n=scan();
            double temp=1;
            while(!isWhiteSpace(n))
            {
                if(n>='0'&&n<='9')
                {
                    temp/=10;
                    doub+=(n-'0')*temp;
                    n=scan();
                }
                else throw new InputMismatchException();
            }
        }
        return doub*neg;
    }
    public String scanString()throws IOException
    {
        StringBuilder sb=new StringBuilder();
        int n=scan();
        while(isWhiteSpace(n))
        n=scan();
        while(!isWhiteSpace(n))
        {
            sb.append((char)n);
            n=scan();
        }
        return sb.toString();
    }
    private boolean isWhiteSpace(int n)
    {
        if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
        return true;
        return false;
    }
}


import java.util.*;
import java.io.*;

public class Main {

    public static void main(String [] args) throws IOException{
        FastScanner sc=new FastScanner();
        int k=sc.nextInt();
        int n=sc.nextInt();
        int [] a=sc.nextIntArray(n);
        List<Integer> list=new ArrayList<>();
        list.add(k-a[0]);
        for(int i=0;i<n-1;i++)list.add(a[i+1]-a[i]);
        list.add(k-a[n-1]);
        list.sort((x,y)->x-y);
        long sum=0;
        for(int i=0;i<n-1;i++)sum+=(long)list.get(i);

        System.out.println(sum);

    }

}

class FastScanner{
    private int BUFFER_SIZE = 1 << 16;

   private  DataInputStream din;

   private  byte[] buffer;

   private int bufferPointer, bytesRead;

   public FastScanner() {
       din = new DataInputStream(System.in);
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public FastScanner( String file_name) throws IOException {
       din = new DataInputStream(new FileInputStream(file_name));
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public String readLine() throws IOException {
        byte[] buf = new byte[64];
       int cnt = 0, c;
       while ((c = read()) != -1) {
           if (c == '\n')
               break;
           buf[cnt++] = (byte) c;
       }
       return new String(buf, 0, cnt);
   }

   public String next() throws IOException{

       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }

        StringBuilder builder = new StringBuilder();
       builder.append((char)c);
       c = read();
       while(!Character.isWhitespace(c)){
           builder.append((char)c);
           c = read();
       }

       return builder.toString();
   }

   public int nextInt() throws IOException {
       int ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (neg)
           return -ret;
       return ret;
   }

   public int[] nextIntArray( int n) throws IOException {
        int arr[] = new int[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextInt();
       }
       return arr;
   }

   public long nextLong() throws IOException {
       long ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');
       if (neg)
           return -ret;
       return ret;
   }

   public long[] nextLongArray( int n) throws IOException {
        long arr[] = new long[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextLong();
       }
       return arr;
   }

   public char nextChar() throws IOException{
       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }
       return (char) c;
   }

   public double nextDouble() throws IOException {
       double ret = 0, div = 1;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();

       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (c == '.') {
           while ((c = read()) >= '0' && c <= '9') {
               ret += (c - '0') / (div *= 10);
           }
       }

       if (neg)
           return -ret;
       return ret;
   }

   public double[] nextDoubleArray( int n) throws IOException {
        double arr[] = new double[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextDouble();
       }
       return arr;
   }

   private void fillBuffer() throws IOException {
       bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
       if (bytesRead == -1)
           buffer[0] = -1;
   }

   private byte read() throws IOException {
       if (bufferPointer == bytesRead)
           fillBuffer();
       return buffer[bufferPointer++];
   }

   public void close() throws IOException {
       if (din == null)
           return;
       din.close();
   }

}


import java.util.*;
import java.io.*;

public class Main  {

    public static void main(String [] args) throws IOException{
        FastScanner sc=new FastScanner();
        int k=sc.nextInt();
        int n=sc.nextInt();
        int [] a=sc.nextIntArray(n);
        List<Integer> list=new ArrayList<>();
        for(int i=1;i<n;i++)list.add(a[i]-a[i-1]);
        list.add(k-a[n-1]);
        list.sort((x,y)->x-y);
        long sum=0;
        for(int i=0;i<list.size()-1;i++){
            sum+=(long)(list.get(i));
        }
        System.out.println(sum);

    }

}

class FastScanner{
    private int BUFFER_SIZE = 1 << 16;

   private  DataInputStream din;

   private  byte[] buffer;

   private int bufferPointer, bytesRead;

   public FastScanner() {
       din = new DataInputStream(System.in);
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public FastScanner( String file_name) throws IOException {
       din = new DataInputStream(new FileInputStream(file_name));
       buffer = new byte[BUFFER_SIZE];
       bufferPointer = bytesRead = 0;
   }

   public String readLine() throws IOException {
        byte[] buf = new byte[64];
       int cnt = 0, c;
       while ((c = read()) != -1) {
           if (c == '\n')
               break;
           buf[cnt++] = (byte) c;
       }
       return new String(buf, 0, cnt);
   }

   public String next() throws IOException{

       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }

        StringBuilder builder = new StringBuilder();
       builder.append((char)c);
       c = read();
       while(!Character.isWhitespace(c)){
           builder.append((char)c);
           c = read();
       }

       return builder.toString();
   }

   public int nextInt() throws IOException {
       int ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (neg)
           return -ret;
       return ret;
   }

   public int[] nextIntArray( int n) throws IOException {
        int arr[] = new int[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextInt();
       }
       return arr;
   }

   public long nextLong() throws IOException {
       long ret = 0;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();
       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');
       if (neg)
           return -ret;
       return ret;
   }

   public long[] nextLongArray( int n) throws IOException {
        long arr[] = new long[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextLong();
       }
       return arr;
   }

   public char nextChar() throws IOException{
       byte c = read();
       while(Character.isWhitespace(c)){
           c = read();
       }
       return (char) c;
   }

   public double nextDouble() throws IOException {
       double ret = 0, div = 1;
       byte c = read();
       while (c <= ' ')
           c = read();
        boolean neg = (c == '-');
       if (neg)
           c = read();

       do {
           ret = ret * 10 + c - '0';
       } while ((c = read()) >= '0' && c <= '9');

       if (c == '.') {
           while ((c = read()) >= '0' && c <= '9') {
               ret += (c - '0') / (div *= 10);
           }
       }

       if (neg)
           return -ret;
       return ret;
   }

   public double[] nextDoubleArray( int n) throws IOException {
        double arr[] = new double[n];
       for(int i = 0; i < n; i++){
           arr[i] = nextDouble();
       }
       return arr;
   }

   private void fillBuffer() throws IOException {
       bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
       if (bytesRead == -1)
           buffer[0] = -1;
   }

   private byte read() throws IOException {
       if (bufferPointer == bytesRead)
           fillBuffer();
       return buffer[bufferPointer++];
   }

   public void close() throws IOException {
       if (din == null)
           return;
       din.close();
   }

}


import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FastScanner fs = new FastScanner();
        int K = fs.nextInt();
        int N = fs.nextInt();
        int[] arr = new int[N];
        int[] dist = new int[N];

        for (int i = 0; i < N; ++i) {
            arr[i] = fs.nextInt();
        }
        Arrays.sort(arr);

        for (int i = 0; i < N; ++i) {
            if (i == N-1) {
                dist[i] = K - arr[i] + arr[0];
            }
            else {
                dist[i] = arr[i+1] - arr[i];
            }
        }

        int ans = Integer.MAX_VALUE;
        for (int i = 0; i < N; ++i) {
            int tmp = 0;
            for (int j = 0; j < N-1; ++j) {
                tmp += dist[(i+j) % N];
            }
            ans = Math.min(ans, tmp);
        }

        System.out.println(ans);
    }
}

class FastScanner {
    private final InputStream in = System.in;
    private final byte[] buffer = new byte[1024];
    private int ptr = 0;
    private int buflen = 0;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        }else{
            ptr = 0;
            try {
                buflen = in.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen <= 0) {
                return false;
            }
        }
        return true;
    }

    private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
    private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
    public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}

    public String next() {
        if (!hasNext()) throw new NoSuchElementException();
        StringBuilder sb = new StringBuilder();
        int b = readByte();
        while(isPrintableChar(b)) {
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    public long nextLong() {
        if (!hasNext()) throw new NoSuchElementException();
        long n = 0;
        boolean minus = false;
        int b = readByte();
        if (b == '-') {
            minus = true;
            b = readByte();
        }
        if (b < '0' || '9' < b) {
            throw new NumberFormatException();
        }
        while(true){
            if ('0' <= b && b <= '9') {
                n *= 10;
                n += b - '0';
            }else if(b == -1 || !isPrintableChar(b)){
                return minus ? -n : n;
            }else{
                throw new NumberFormatException();
            }
            b = readByte();
        }
    }

    public int nextInt() {
        long nl = nextLong();
        if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
        return (int) nl;
    }

    public double nextDouble() { return Double.parseDouble(next());}
}


#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int CM = 130000;
char cn[CM + 10], * ci = cn + 10, *owa = cn + CM;
const ll ma0 = 1157442765409226768;
const ll ma1 = 1085102592571150095;
const ll ma2 = 71777214294589695;
const ll ma3 = 281470681808895;
const ll ma4 = 4294967295;
inline int getint() {
	ll tmp = *(ll*)ci;
	int dig = 68 - __builtin_ctzll((tmp & ma0) ^ ma0);
	tmp = tmp << dig & ma1;
	tmp = tmp * 10 + (tmp >> 8) & ma2;
	tmp = tmp * 100 + (tmp >> 16) & ma3;
	tmp = tmp * 10000 + (tmp >> 32) & ma4;
	ci += (64 - dig >> 3) + 1;
	if (ci - owa > 0) {
		memcpy(cn, owa, 10);
		ci -= CM;
		fread(cn + 10, 1, CM, stdin);
	}
	return tmp;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);

	fread(ci, 1, CM, stdin);
	int K = getint();
	int N = getint();
	int A0 = getint();
	int mae = A0;
	int kotae = 0;
	rep(i, N - 1) {
		int a = getint();
		chmax(kotae, a - mae);
		mae = a;
	}

	chmax(kotae, A0 + K - mae);

	printf("%d", K - kotae);

	Would you please return 0;
}


/*                         _
                        _ooOoo_
                       o8888888o
                       88" . "88
                       (| -_- |)
                       O\  =  /O
                    ____/`---'\____
                  .'  \\|     |//  `.
                 /  \\|||  :  |||//  \
                /  _||||| -:- |||||_  \
                |   | \\\  -  /'| |   |
                | \_|  `\`---'//  |_/ |
                \  .-\__ `-. -'__/-.  /
              ___`. .'  /--.--\  `. .'___
           ."" '<  `.___\_<|>_/___.' _> \"".
          | | :  `- \`. ;`. _/; .'/ /  .' ; |
          \  \ `-.   \_\_`. _.'_/_/  -' _.' /
===========`-.`___`-.__\ \___  /__.-'_.'_.-'================

                  Please give me AC.
*/

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <string>
#include <sstream>
#include <complex>
#include <bitset>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <chrono>
#include <random>

using namespace std;

using int64 = long long;
using uint64 = unsigned long long;
using vi = vector<int>;
using vl = vector<int64>;
using pii = pair<int, int>;
using pll = pair<int64, int64>;

#define rep(i, n) for (int i = 0; i < (int)(n); ++i)
#define all(v) (v).begin(), (v).end()
#define print(x) cout << (x) << '\n'
#define print2(x, y) cout << (x) << ' ' << (y) << '\n'
#define print3(x, y, z) cout << (x) << ' ' << (y) << ' ' << (z) << '\n'
#define printn(v) rep(i, (v).size() - 1) cout << (v)[i] << ' '; cout << (v)[n - 1] << '\n';
#define debug(x) cerr << #x << ": " << (x) << '\n'
#define debug2(x, y) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << '\n'
#define debug3(x, y, z) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << ", " << #z << ": " << (z) << '\n'
#define dbg(v) for (size_t _ = 0; _ < v.size(); ++_){cerr << #v << "[" << _ << "] : " << v[_] << '\n';}
// constant
const int INF = (1<<30) - 1;
const int64 INF64 = (1LL<<62) - 1;

template<typename T> T gcd(T a, T b) {
    if (a < b) return gcd(b, a);
    T r;
    while ((r = a % b)) {
        a = b;
        b = r;
    }
    return b;
}

template<typename T> T lcm(const T a, const T b) {
    return a / gcd(a, b) * b;
}

template<typename T> bool chmin(T& a, const T& b) {
    if (a > b) return a = b, true; else return false;
}

template<typename T> bool chmax(T& a, const T& b) {
    if (a < b) return a = b, true; else return false;
}

// End of template.

// begin fast io

char buf[10000000], OUT[10000000];
int bufi = 0, outi = 0;

template<typename T>
void readui(T &n) {
    n = 0;
    int c = buf[bufi++];
    for (; '0' <= c && c <= '9'; c = buf[bufi++])
        n = 10 * n + c - '0';
}

template<typename T>
void readi(T &n) {
    bool negative = false;
    if (buf[bufi] == '-') negative = true, bufi++;
    readui(n);
    if (negative) n = -n;
}

template<typename T>
void readuf(T &x) {
    x = 0;
    T y = 0;
    int z = 0;
    int c = buf[bufi++];
    for (; '0' <= c && c <= '9'; c = buf[bufi++])
        x = 10 * x + c - '0';
    if (buf[bufi - 1] == '.')
        for (; '0' <= c && c <= '9'; c = buf[bufi++], ++z)
            y = 10 * y + c - '0';
    x += y / pow(10, z);
}

template<typename T>
void readf(T &x) {
    bool negative = false;
    if (buf[bufi] == '-') negative = true, bufi++;
    readuf(x);
    if (negative) x = -x;
}

void reads(string &s) {
    const int begin = bufi;
    int c;
    while (c = buf[bufi++], c != ' ' && c != '\n') {}
    s = string(buf + begin, buf + bufi);
}

void readline(string &s) {
    const int begin = bufi;
    while (buf[bufi++] != '\n') {}
    s = string(buf + begin, buf + bufi);
}

const char digit_pairs[] = {
  "00010203040506070809"
  "10111213141516171819"
  "20212223242526272829"
  "30313233343536373839"
  "40414243444546474849"
  "50515253545556575859"
  "60616263646566676869"
  "70717273747576777879"
  "80818283848586878889"
  "90919293949596979899"
};

template<typename T>
void writeui(T n) {
    if (n == 0) OUT[outi++] = '0';
    int size;
    if (n >= 1e12) {
        if (n >= 1e16) {
            if (n >= 1e18) {
                if (n >= 1e19) size = 20;
                else size = 19;
            } else {
                if (n >= 1e17) size = 18;
                else size = 17;
            }
        } else {
            if (n >= 1e14) {
                if (n >= 1e15) size = 16;
                else size = 15;
            } else {
                if (n >= 1e13) size = 14;
                else size = 13;
            }
        }
    } else if (n >= 1e4) {
        if (n >= 1e8) {
            if (n >= 1e10) {
                if (n >= 1e11) size = 12;
                else size = 11;
            } else {
                if (n >= 1e9) size = 10;
                else size = 9;
            }
        } else {
            if (n >= 1e6) {
                if (n >= 1e7) size = 8;
                else size = 7;
            } else {
                if (n >= 1e5) size = 6;
                else size = 5;
            }
        }
    } else {
        if (n >= 1e2) {
            if (n >= 1e3) size = 4;
            else size = 3;
        } else {
            if (n >= 1e1) size = 2;
            else size = 1;
        }
    }
    char *c = OUT + outi + size;
    outi += size;
    while (n >= 100) {
        int x = n % 100;
        n /= 100;
        *--c = digit_pairs[2 * x + 1];
        *--c = digit_pairs[2 * x];
    }
    while (n > 0) {
        *--c = '0' + (n % 10);
        n /= 10;
    }
}

// end fast io

int main() {
    cout << fixed << setprecision(15);
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cin.read(buf, sizeof buf); // 注意: ./a.out < in か pbp | ./a.out で入力すること

    int n, k, total = 0;
    readui(k), readui(n);
    int f, a, b, t;
    readui(f);
    t = a = f;

    rep(i, n - 1) {
        readui(b);
        chmax(t, b - a);
        swap(a, b);
    }

    chmax(t, k + f - a);
    print(k - t);

    return 0;
}


#include <bits/stdc++.h>

class kin{
public:
	inline void open(FILE *,int);
	inline void close(void);
	inline void scan(void);
	inline kin &operator>(char &);
	inline kin &operator>(int &);
	inline kin &operator>(long long &);
	inline kin &operator>(double &);
	inline kin &operator>(long double &);
	inline kin &operator>(char *);
	template<class T>
	inline void get(T *,int);
private:
	FILE *fp;
	char *buf;
	int siz;
	int idx;
}in;

class kout{
public:
	inline void open(FILE *,int);
	inline void close(void);
	inline void print(void);
	inline kout &operator<(char);
	inline kout &operator<(int);
	inline kout &operator<(long long);
	inline kout &operator<(double);
	inline kout &operator<(long double);
	inline kout &operator<(const char *);
	template<class T>
	inline void put(T *,int,char,char);
private:
	FILE *fp;
	char *buf;
	int siz;
	int idx;
}out;

inline void chmax(int val,int &dat){
	if(val>dat) dat=val;
}

int main(int argc,char **argv){
	in.open(stdin,512);
	out.open(stdout,512);
	in.scan();
	int k,n;
	in>k>n;
	int a1;
	in>a1;
	int p=a1,d=0,an;
	for(int i=1;i<n;++i){
		in>an;
		chmax(an-p,d);
		p=an;
	}
	chmax(k+a1-an,d);
	out<k-d<'\n';
	out.print();
	in.close();
	out.close();
	return 0;
}

inline void kin::open(FILE *fpa,int siza){
	fp=fpa;
	buf=new char[siza];
	siz=siza;
	idx=0;
	return;
}
inline void kin::close(void){
	fp=nullptr;
	delete[] buf;
	buf=nullptr;
	siz=0;
	idx=0;
	return;
}
inline void kin::scan(void){
	int readsiz=(int)std::fread((void *)buf,(std::size_t)1,(std::size_t)siz,fp);
	if(readsiz!=siz) buf[readsiz]='\x00';
	idx=0;
	return;
}
inline kin &kin::operator>(char &var){
	if(!buf[idx]){
		var='\x00';
		return *this;
	}
	var=buf[idx];
	if(++idx==siz) scan();
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(int &var){
	if(!buf[idx]){
		var=0;
		return *this;
	}
	int sign=-1;
	if(buf[idx]=='-'){
		sign=1;
		if(++idx==siz) scan();
	}
	var=0;
	while(buf[idx]>='0'){
		var=var*10-(int)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(long long &var){
	if(!buf[idx]){
		var=0LL;
		return *this;
	}
	long long sign=-1LL;
	if(buf[idx]=='-'){
		sign=1LL;
		if(++idx==siz) scan();
	}
	var=0LL;
	while(buf[idx]>='0'){
		var=var*10LL-(long long)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(double &var){
	if(!buf[idx]){
		var=0.0;
		return *this;
	}
	double sign=-1.0;
	if(buf[idx]=='-'){
		sign=1.0;
		if(++idx==siz) scan();
	}
	var=0.0;
	while(buf[idx]>='0'){
		var=var*10.0-(double)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	if(buf[idx]=='.'){
		if(++idx==siz) scan();
		double dig=1.0;
		while(buf[idx]>='0'){
			var-=(double)(buf[idx]-'0')*(dig/=10.0);
			if(++idx==siz) scan();
		}
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(long double &var){
	if(!buf[idx]){
		var=0.0L;
		return *this;
	}
	long double sign=-1.0L;
	if(buf[idx]=='-'){
		sign=1.0L;
		if(++idx==siz) scan();
	}
	var=0.0L;
	while(buf[idx]>='0'){
		var=var*10.0L-(long double)(buf[idx]-'0');
		if(++idx==siz) scan();
	}
	if(buf[idx]=='.'){
		if(++idx==siz) scan();
		long double dig=1.0L;
		while(buf[idx]>='0'){
			var-=(long double)(buf[idx]-'0')*(dig/=10.0L);
			if(++idx==siz) scan();
		}
	}
	var*=sign;
	if(++idx==siz) scan();
	return *this;
}
inline kin &kin::operator>(char *var){
	if(!buf[idx]){
		var[0]='\x00';
		return *this;
	}
	int ptr=0;
	while(buf[idx]>='!'){
		var[ptr++]=buf[idx];
		if(++idx==siz) scan();
	}
	var[ptr]='\x00';
	if(++idx==siz) scan();
	return *this;
}
template<class T>
inline void kin::get(T *var,int num){
	for(int i=0;i<num;++i) (*this)>var[i];
	return;
}

inline void kout::open(FILE *fpa,int siza){
	fp=fpa;
	buf=new char[siza];
	siz=siza;
	idx=0;
	return;
}
inline void kout::close(void){
	fp=nullptr;
	delete[] buf;
	buf=nullptr;
	siz=0;
	idx=0;
	return;
}
inline void kout::print(void){
	std::fwrite((void *)buf,(std::size_t)1,(std::size_t)idx,fp);
	idx=0;
	return;
}
inline kout &kout::operator<(char val){
	buf[idx]=val;
	if(++idx==siz) print();
	return *this;
}
inline kout &kout::operator<(int val){
	if(val<0){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1;
	char dig[10];
	int ptr=0;
	do{
		int tmp=val/10;
		dig[ptr++]=(char)-(val-tmp*10)+'0';
		val=tmp;
	}while(val);
	while(ptr--){
		buf[idx]=dig[ptr];
		if(++idx==siz) print();
	}
	return *this;
}
inline kout &kout::operator<(long long val){
	if(val<0LL){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1LL;
	char dig[19];
	int ptr=0;
	do{
		long long tmp=val/10LL;
		dig[ptr++]=(char)-(val-tmp*10LL)+'0';
		val=tmp;
	}while(val);
	while(ptr--){
		buf[idx]=dig[ptr];
		if(++idx==siz) print();
	}
	return *this;
}
inline kout &kout::operator<(double val){
	if(val<0.0){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1.0;
	double dig=1.0;
	while(val/dig<=-10.0) dig*=10.0;
	int tmp;
	while(dig>=1.0){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(double)tmp*dig;
		dig/=10.0;
	}
	buf[idx]='.';
	if(++idx==siz) print();
	for(int i=0;i<12;++i){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(double)tmp*dig;
		dig/=10.0;
	}
	return *this;
}
inline kout &kout::operator<(long double val){
	if(val<0.0L){
		buf[idx]='-';
		if(++idx==siz) print();
	}
	else val*=-1.0L;
	long double dig=1.0L;
	while(val/dig<=-10.0L) dig*=10.0L;
	int tmp;
	while(dig>=1.0L){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(long double)tmp*dig;
		dig/=10.0L;
	}
	buf[idx]='.';
	if(++idx==siz) print();
	for(int i=0;i<16;++i){
		buf[idx]=(char)-(tmp=(int)(val/dig))+'0';
		if(++idx==siz) print();
		val-=(long double)tmp*dig;
		dig/=10.0L;
	}
	return *this;
}
inline kout &kout::operator<(const char *val){
	for(int i=0;val[i];++i){
		buf[idx]=val[i];
		if(++idx==siz) print();
	}
	return *this;
}
template<class T>
inline void kout::put(T *val,int num,char dlm,char end){
	--num;
	for(int i=0;i<num;++i) (*this)<val[i]<dlm;
	(*this)<val[num]<end;
	return;
}


#include <bits/stdc++.h>
using namespace std;
#define watch(x) cout << (#x) << " is " << (x) << '\n'
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_bacm
#define mp mame_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define sz(x) ((int)(x).size())
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pll;
typedef double db;
ll gcd(ll a, ll b) { return b?gcd(b,a%b):a; }
//head

void solve(){
    int k, n;
    cin >> k >> n;
    vector<int> a(n);
    ll s = 0;
    for (int i = 0; i < n; i++){
        cin >> a[i];
        a[i] = a[i] % (k/2);
        s += a[i];
    }
    cout << s << '\n';
}

int main(void){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);

    //int t; cin >> t; while (t--)
        solve();
}


#include<bits/stdc++.h>

using namespace std;

int main(){
int n, i, right, left, ans = 0, k;
cin >> k >> n;
int a[n];
right = 0; left = k;
for(i=0; i<n; i++) cin >> a[i];
for(i=0; i<n; i++){
    if(a[i]!=0) left = min(left, a[i]);
    if(a[i]!=k) right = max(right, a[i]);
}
ans = min(k-abs(right-left), abs(right-left));
cout << ans;

}


#include<bits/stdc++.h>

using namespace std;

int main(){
int n, i, right=INT_MIN, left=INT_MAX, ans = 0, k;
cin >> k >> n;
int a[n];
for(i=0; i<n; i++) cin >> a[i];
for(i=0; i<n; i++){
    if(a[i]!=0) left = min(left, a[i]);
    if(a[i]!=k) right = max(right, a[i]);
}
ans = min(k-(right-left), abs(right-left));
cout << ans;

}


// ABC 160-C
// 2020.3.28 bal4u

#include <stdio.h>

#define gc() getchar_unlocked()
int in() {   // 非負整数の入力
	int n = 0, c = gc();
	do n = 10 * n + (c & 0xf); while ((c = gc()) >= '0');
	return n;
}

int A[200005]; int N;
int main()
{
	int i, K, t, ans;

	K = in(), N = in();
	ans = 0;
	A[0] = in();
	for (i = 1; i < N; ++i) {
		A[i] = in();
		if (A[i]-A[i-1] > ans) ans = A[i]-A[i-1];
	}
	if (K-A[N-1]+A[0] > ans) ans = K-A[N-1]+A[0];
	printf("%d\n", K-ans);
	return 0;
}


#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>

#define P 1000000007

int comp(const void *a, const void *b){return *(int*)a-*(int*)b;}
int compw(const void *a, const void *b){return (*(int*)a>*(int*)b)-(*(int*)a<*(int*)b);}
int compr(const void *a, const void *b){return *(int*)b-*(int*)a;}

uint32_t nextpint(void){ char c=getchar(); while(c<'0'||'9'<c) c=getchar(); uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }

inline int max2(const int a, const int b){return a>b?a:b;}
inline int min2(const int a, const int b){return a>b?b:a;}
inline int dif2(const int a, const int b){return a>b?a-b:b-a;}

int main(void){
	int k=nextpint();
	int n=nextpint();
	int a, b;
	int ans=0;
	int f=b=nextpint();
	for(int i=1; i<n; i++){
		a=nextpint();
		int now=a-b;
		if(now>ans) ans=now;
		b=a;
	}
	int now=k+f-b;
	if(now>ans) ans=now;
	printf("%d\n", k-ans);
}


#include <float.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>

#define P 1000000007

int comp(const void *a, const void *b){return *(int*)a-*(int*)b;}
int compw(const void *a, const void *b){return (*(int*)a>*(int*)b)-(*(int*)a<*(int*)b);}
int compr(const void *a, const void *b){return *(int*)b-*(int*)a;}

uint32_t nextpint(void){ char c=getchar(); while(c<'0'||'9'<c) c=getchar(); uint32_t x=0; while('0'<=c && c<='9'){ x=x*10+c-'0'; c=getchar(); } return x; }
uint32_t nextstr(char *s){ char c=getchar(); while(c==' '||c=='\n') c=getchar(); uint32_t len=0; while(c!=' '&&c!='\n'){ *s++=c; len++; c=getchar(); } *s='\0'; return len; }

inline int max2(const int a, const int b){return a>b?a:b;}
inline int min2(const int a, const int b){return a>b?b:a;}
inline int dif2(const int a, const int b){return a>b?a-b:b-a;}

int a[200000];
int main(void){
	int k=nextpint();
	int n=nextpint();
	for(int i=0; i<n; i++){
		a[i]=nextpint();
	}
	int ans=k+a[0]-a[n-1];
	for(int i=0; i<n-1; i++){
		int now=a[i+1]-a[i];
		if(now>ans) ans=now;
	}
	printf("%d\n", k-ans);
}


#include <stdio.h>

int main(void){
  int n,k,max=0;
  int a[100005];

  scanf("%d %d", &k, &n);
  //scanf("%lld", &k);

  for(int i =0;i<n;i++){
    scanf("%d", &a[i]);
  }

  max = k-a[n-1]+a[0];

  for(int i=0;i<n-1;i++){
    if(max<a[i+1]-a[i]) max = a[i+1]-a[i];
  }

  printf("%d", k-max);
  return 0;
}


#include <stdio.h>

int main(void){
  long int n,k,max=0;
  long int a[100005];

  scanf("%ld %ld", &k, &n);
  //scanf("%lld", &k);

  for(int i =0;i<n;i++){
    scanf("%ld", &a[i]);
  }

  max = k-a[n-1]+a[0];

  for(int i=0;i<n-1;i++){
    if(max<a[i+1]-a[i]) max = a[i+1]-a[i];
  }

  printf("%d", k-max);
  return 0;
}


#include <stdio.h>

int main(void){
  long long int n,k,max=0;
  long long int a[100005];

  scanf("%lld %lld", &k, &n);
  //scanf("%lld", &k);

  for(int i =0;i<n;i++){
    scanf("%lld", &a[i]);
  }

  max = k-a[n-1]+a[0];

  for(int i=0;i<n-1;i++){
    if(max<a[i+1]-a[i]) max = a[i+1]-a[i];
  }

  printf("%d", k-max);
  return 0;
}


  // inputに入力データ全体が入る
  function Main(input) {
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.split("\n");
	tmp = input[0].split(" ");
  var K = Number(tmp[0]);
  var N = Number(tmp[1]);
	//文字列から10進数に変換するときはparseIntを使います
  tmp = input[1].split(" ");
  for(i=0; i<tmp.length; i++){
    tmp[i] = Number(tmp[i]);
  }

  var max = 0;
  for (var i = 1; i < tmp.length; i++) {
    dis = tmp[i] - tmp[i-1];
    if(dis > max) max = dis;
  }
  dis = K - (tmp[tmp.length-1] - tmp[0]);
  if(dis > max) max = dis;
	//出力
	console.log('%d', K-max);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    // 1行目がinput[0], 2行目がinput[1], …に入る
    var S = input.split('\n');
    var K = S[0].split(' ')[0];
    var N = S[0].split(' ')[1];
    var A = S[1].split(' ');
    var count = 0;
    for (var i = 0; i < N; i++) {
        var sa = A[i] - A[i + 1];
        if (Math.abs(sa) > count) {
            count = Math.abs(sa);
        }
    }
    if (K - (A[N - 1] - A[0]) > count) {
        count = K - (A[N - 1] - A[0]);
    }
    console.log(K - count);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";

const main = arg => {
    arg = arg.trim().split("\n");
    const K = Number(arg[0].split(" ")[0]);
    const N = Number(arg[0].split(" ")[1]);
    const A = arg[1].split(" ").map(Number);

    let longestDistances = 0;

    // 区間を作る
    for(let i=0; i<N; i++) {
        let distance;

        if(Number(i) === N - 1) {
            distance = (K - A[i]) + A[0];
        } else {
            distance = A[Number(i) + 1] - A[i];
        }

        if(longestDistances < distance) {
            longestDistances = distance;
        }
    }

    const answer = K - longestDistances;

    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input = require("fs").readFileSync("/dev/stdin", "utf8")

;(input => {

    const lines = input.split('\n')
    const [K, N] = lines[0].split(' ').map(Number)
    const A = lines[1].split(' ').map(Number)

    const diff = []
    diff[0] = A[0] + K - A[N - 1]
    for (let i = 1; i < N; i++) {
        diff[i] = A[i] - A[i - 1]
    }
    console.log(K - Math.max(...diff))

})(input)


process.stdin.resume();
process.stdin.setEncoding('utf8');

var lines = []
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

reader.on('line', (line) => {
  lines.push(line);
});

reader.on('close', () => {
 var kn = lines[0].split(' ');
 var k = Number(kn[0]);
 var n = Number(kn[1]);
 var a = lines[1].split(' ');
 a = a.map(function(str) { return Number(str)});
 // console.log(a);
 var kyori = [];
 kyori.push(k+a[0] - a[n-1]);

 for(i=0; i<n-1; i++){
   kyori.push(a[i+1] - a[i]);
 }

 // console.log(kyori);
 var max = Math.max(...kyori);
 var index = kyori.indexOf(max);
 kyori.splice(index,1);
 // console.log(kyori);
 var ans = kyori.reduce(function(a, x){return a + x;});
 console.log(ans);
});


process.stdin.resume();
process.stdin.setEncoding('utf8');

var lines = []
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

reader.on('line', (line) => {
  lines.push(line);
});

reader.on('close', () => {
 var kn = lines[0].split(' ');
 var k = Number(kn[0]);
 var n = Number(kn[1]);
 var a = lines[1].split(' ');
 // console.log(a);
 var kyori = [];
 kyori.push(k+a[0] - a[n-1]);

 for(i=0; i<n-1; i++){
   kyori.push(a[i+1] - a[i]);
 }

 // console.log(kyori);
 var max = Math.max(...kyori);
 var index = kyori.indexOf(max);
 kyori.splice(index,1);
 // console.log(kyori);
 var ans = kyori.reduce(function(a, x){return a + x;});
 console.log(ans);
});


package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

type BufferedWriter interface {
    Printf(format string, a ...interface{})
    Flush()
}

type writerImpl struct {
    *bufio.Writer
}

func NewBufferedWriter(writer io.Writer) BufferedWriter {
    return &writerImpl{Writer: bufio.NewWriter(writer)}
}

func (impl *writerImpl) Printf(f string, a ...interface{}) {
    fmt.Fprintf(impl.Writer, f, a...)
}

func (impl *writerImpl) Flush() {
    impl.Writer.Flush()
}

type WordScanner interface {
    NextInt() int
    NextInt64() int64
    NextString() string
}

type wordScannerImpl struct {
    *bufio.Scanner
}

func NewWordScanner(reader io.Reader) WordScanner {
    s := bufio.NewScanner(reader)
    s.Split(bufio.ScanWords)
    return &wordScannerImpl{Scanner: s}
}

func (impl *wordScannerImpl) NextInt() int {
    impl.Scan()
    bb := impl.Bytes()
    i := 0
    for _, b := range bb {
        i *= 10
        i += int(b - '0')
    }
    return i
}

func (impl *wordScannerImpl) NextInt64() int64 {
    impl.Scan()
    bb := impl.Bytes()
    i := int64(0)
    for _, b := range bb {
        i *= 10
        i += int64(b - '0')
    }
    return i
}

func (impl *wordScannerImpl) NextString() string {
    impl.Scan()
    return impl.Text()
}

var reader = NewWordScanner(os.Stdin)
var writer = NewBufferedWriter(os.Stdout)

func main() {
    defer writer.Flush()
    k, n := reader.NextInt64(), reader.NextInt64()
    aa := make([]int64, n)
    for i := int64(0); i < n; i++ {
        aa[i] = reader.NextInt64()
    }
    diffToPrev := make([]int64, n)
    diffToPrev[0] = aa[0] + k - aa[len(aa)-1]
    for i := int64(1); i < n; i++ {
        diffToPrev[i] = aa[i] - aa[i-1]
    }
    maxSoFar := diffToPrev[0]
    for i := int64(1); i < n; i++ {
        if diffToPrev[i] > maxSoFar {
            maxSoFar = diffToPrev[i]
        }
    }
    writer.Printf("%d\n", k - maxSoFar)
}


package main

import (
	"bufio"
	"fmt"
	"io"
	"math"
	"os"
	"strconv"
	"strings"

)

func main() {
	solve(os.Stdin, os.Stdout)
}

type ReaderEx struct {
	baseScanner *bufio.Scanner
	words       []string
	nextWordIdx func() int
	initWordIdx func(int)
}

func NewScannerEx(stdin io.Reader) *ReaderEx {
	var this ReaderEx
	var idx int
	var wordsCnt int
	this.baseScanner = bufio.NewScanner(stdin)
	this.baseScanner.Buffer(make([]byte, 0), 1E+11)
	this.nextWordIdx = func() int {
		cur := idx
		idx = (idx + 1) % wordsCnt
		return cur
	}
	this.initWordIdx = func(wc int) {
		idx = 0
		wordsCnt = wc
	}
	return &this
}

func (me *ReaderEx) Scan(doSplit bool) (isScanned bool) {
	isScanned = me.baseScanner.Scan()
	if doSplit {
		me.words = strings.Fields(me.baseScanner.Text())
	} else {
		me.words = []string{me.baseScanner.Text()}
	}
	me.initWordIdx(len(me.words))
	return
}

func (me *ReaderEx) nextBytes() []byte {
	return []byte(me.words[me.nextWordIdx()])
}
func (me *ReaderEx) nextString() string {
	return me.words[me.nextWordIdx()]
}

type StringArray []string

func (me *ReaderEx) nextStringArray() StringArray {
	return me.words[me.nextWordIdx():]
}

func (me StringArray) toStrings() []string {
	return me
}

func (me StringArray) toInts() []int {
	strValues := me.toStrings()
	values := make([]int, len(strValues))
	for i, v := range strValues {
		n, err := strconv.Atoi(v)
		if err != nil {
			panic(err)
		}
		values[i] = n
	}
	return values
}
func (me *ReaderEx) nextInt() int {
	n, err := strconv.Atoi(me.words[me.nextWordIdx()])

	defer func() {
		if err != nil {
			panic(fmt.Sprintf("getInt(%d)", n))
		}
	}()
	return n
}

func pow(x, y, mod int) (ans int) {

	ans = 1
	for bit := 1 << uint(math.Floor(math.Log2(float64(y)))); ; bit >>= 1 {
		if y&bit != 0 {
			ans *= x
			if mod > 0 {
				ans %= mod
			}
		}
		if bit <= 1 {
			return
		}
		ans *= ans
		if mod > 0 {
			ans %= mod
		}
	}
}

type factType struct {
	prime int
	count int
}

func fact(n int) (facts []*factType) {

	for i := 2; i*i <= n; i++ {
		if n%i == 0 {
			fa := factType{prime: i}
			for n%fa.prime == 0 {
				n /= fa.prime
				fa.count++
			}
			facts = append(facts, &fa)
		}
	}
	if n > 1 {
		facts = append(facts, &factType{prime: n, count: 1})
	}
	return facts
}
func dec2bin(n int) (ret []bool) {
	for bit := 1 << uint(math.Floor(math.Log2(float64(n)))); ; bit >>= 1 {
		ret = append(ret, n&bit != 0)

		if bit <= 1 {
			return
		}
	}

}

func abs(v int) int {
	if v < 0 {
		v = -v
	}
	return v
}

func b2i(b bool) (i int) {
	if b {
		i = 1
	} else {
		i = 0
	}
	return
}

func solve(stdin io.Reader, stdout io.Writer) {

	r := NewScannerEx(stdin)
	r.Scan(true)
	k, n := r.nextInt(), r.nextInt()
	r.Scan(true)
	a := r.nextStringArray().toInts()

	m := k - a[n-1] + a[0]
	for i := 1; i < n; i++ {
		w := a[i] - a[i-1]
		if m < w {
			m = w
		}
	}
	fmt.Fprintln(stdout, k-m)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func configure(scanner *bufio.Scanner) {
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 1000005), 1000005)
}
func getNextString(scanner *bufio.Scanner) string {
	scanned := scanner.Scan()
	if !scanned {
		panic("scan failed")
	}
	return scanner.Text()
}
func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}
func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}
func getNextFloat64(scanner *bufio.Scanner) float64 {
	i, _ := strconv.ParseFloat(getNextString(scanner), 64)
	return i
}
func main() {
	fp := os.Stdin
	wfp := os.Stdout
	extra := 0
	if os.Getenv("I") == "IronMan" {
		fp, _ = os.Open(os.Getenv("END_GAME"))
		extra = 100
	}
	scanner := bufio.NewScanner(fp)
	configure(scanner)
	writer := bufio.NewWriter(wfp)
	defer func() {
		r := recover()
		if r != nil {
			fmt.Fprintln(writer, r)
		}
		writer.Flush()
	}()
	solve(scanner, writer)
	for i := 0; i < extra; i++ {
		fmt.Fprintln(writer, "-----------------------------------")
		solve(scanner, writer)
	}
}
func solve(scanner *bufio.Scanner, writer *bufio.Writer) {
	k := getNextInt(scanner)
	n := getNextInt(scanner)
	aa := make([]int, n+1)
	for i := 0; i < n; i++ {
		aa[i] = getNextInt(scanner)
	}
	aa[n] = k + aa[0]
	var ans int
	ans = k
	for i := 0; i < n; i++ {
		if ans > k-(aa[i+1]-aa[i]) {
			ans = k - (aa[i+1] - aa[i])
		}
	}
	fmt.Fprintln(writer, ans)
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strconv"
)

func main() {
	sc := newScanner()
	var k = sc.readInt()
	var n = sc.readInt()
	var a = make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = sc.readInt()
	}
	// proc dist
	var dist = make([]int, n)
	for i := 0; i < n; i++ {
		if i != n-1 {
			dist[i] = a[i+1] - a[i]
		} else {
			dist[i] = a[0] + k - a[i]
		}
	}
	var max int = dist[0]
	for i := 0; i < len(dist); i++ {
		if max < dist[i] {
			max = dist[i]
		}
	}
	fmt.Println(max)

}

//////////////////
//////////////////
//////////////////

func abs(x int) int {
	if x >= 0 {
		return x
	}
	return -x
}

func min(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}

	min := values[0]
	for _, v := range values {
		if v < min {
			min = v
		}
	}
	return min
}

func max(values ...int) int {
	if len(values) == 0 {
		panic("no values")
	}

	max := values[0]
	for _, v := range values {
		if v > max {
			max = v
		}
	}
	return max
}

func pow(base, exponent int) int {
	if exponent < 0 {
		panic(fmt.Sprintf("exponent (%d) should not be a minus", exponent))
	}

	answer := 1
	for i := 0; i < exponent; i++ {
		answer *= base
	}
	return answer
}

func ceil(divident, dividor int) int {
	if dividor == 0 {
		panic("dividor should not be 0")
	}

	quo := divident / dividor
	rem := divident % dividor

	if rem != 0 {
		if (divident > 0 && dividor > 0) ||
			(divident < 0 && dividor < 0) {
			return quo + 1
		}
	}
	return quo
}

// -   sortutil

func reverseInts(a []int) {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
}

func reverseStrings(a []string) {
	sort.Sort(sort.Reverse(sort.StringSlice(a)))
}

// -   io

type scanner struct {
	bufScanner *bufio.Scanner
}

func newScanner() *scanner {
	bufSc := bufio.NewScanner(os.Stdin)
	bufSc.Split(bufio.ScanWords)
	bufSc.Buffer(nil, 100000000)
	return &scanner{bufSc}
}

func (sc *scanner) readString() string {
	bufSc := sc.bufScanner
	bufSc.Scan()
	return bufSc.Text()
}

func (sc *scanner) readInt() int {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.Atoi(text)
	if err != nil {
		panic(err)
	}
	return num
}

func (sc *scanner) readInt64() int64 {
	bufSc := sc.bufScanner
	bufSc.Scan()
	text := bufSc.Text()

	num, err := strconv.ParseInt(text, 10, 64)
	if err != nil {
		panic(err)
	}
	return num
}


package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	k := nextInt()
	n := nextInt()
	alist := make([]int, n)
	kukanlist := make([]int, n)
	maxkukan := -1
	roadmax := 0

	for i := 0; i < n; i++ {
		alist[i] = nextInt()
	}
	for i := 1; i < n; i++ {
		kukanlist[i] = alist[i] - alist[i-1]
		roadmax += kukanlist[i]
	}
	kukanlist[0] = k - alist[n-1]
	roadmax += kukanlist[0]

	for i := 0; i < n; i++ {
		if kukanlist[i] > maxkukan {
			maxkukan = kukanlist[i]
		}
	}

	//fmt.Println(kukanlist, roadmax, maxkukan)
	fmt.Println(roadmax - maxkukan)
}

// ---- readfunc
func scanInit() {
	const cap = 64 * 1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}


package main

import (
	"fmt"
)

var K, N, ans, a int
func main() {
	fmt.Scan(&K)
	fmt.Scan(&N)
	for i := 0; i < N; i++ {
		fmt.Scan(&a)
		ans += a % (K / 2)
	}
	fmt.Println(ans)
}


k, n = STDIN.gets.split.map(&:to_i)
a_list = STDIN.gets.split.map(&:to_i)

first_a = a_list.shift
max = 0
before_a = first_a

a_list.each do |a|
  s = a - before_a
  before_a = a
  max = s if s > max
end

last_s = k - a_list[-1] + first_a
max = last_s if last_s > max
puts k - max


k, n = gets.chomp.split(' ').map{|i| i.to_i }

a1 = 0
old = -1
sum = 0
max = 0

alast = gets.chomp.split(' ').map{|i|
  ii = i.to_i
  if old == -1
    a1 = ii
    old = ii
    next
  end
  diff = ii - old
  sum += diff
  max = diff if max < diff
  old = ii
  ii
}.last

uediff = k - (alast - a1)
sum += uediff
max = uediff if max < uediff

puts sum - max


k, n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
max = 0
1.upto(n - 1) do |i|
    d = a[i] - a[i - 1]
    max = d if d > max
end
d0 = k + a[0] - a[n - 1]
max = d0 if d0 > max
puts k - max


k,n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
max = 0
memo = nil
a.each_cons(2).with_index do |ij,idx|
  i,j = ij
  if j-i > max
    max = j-i
    memo = idx
  end
end
memo = -1 if k - a[-1] + a[0] > max
puts k - (a[memo+1] - a[memo]).abs


k,n = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
max = 0
memo = nil
a.each_cons(2).with_index do |ij,idx|
  i,j = ij
  if j-i > max
    max = j-i
    memo = idx
  end
end
if k - a[-1] + a[0] > max
  max = k - a[-1] + a[0]
  memo = -1
end
puts (a[memo+1] - a[memo]).abs


K, N = gets.split.map &:to_i
a = gets.split.map &:to_i

a << K - a.max + a.min
a.sort!
puts K - (0..N).map { |i| a[i] - a[i-1] }.max


use std::cmp::*;
use std::io::*;
use utils::*;

pub fn main() {
    let i = stdin();
    let mut o = Vec::new();
    run(i.lock(), &mut o);
    stdout().write_all(&o).unwrap();
}

pub fn run<R: BufRead, W: Write>(i: R, o: &mut W) {
    let mut i = CpReader::new(i);
    let (k, n) = i.read::<(usize, usize)>();
    let a = i.read_vec::<usize>(n);
    writeln!(o, "{}", solve(k, a)).unwrap();
}
fn solve(k: usize, mut a: Vec<usize>) -> usize {
    let end = k + a[0];
    a.push(end);
    let mut d = 0;
    for i in 1..a.len() {
        d = max(d, a[i] - a[i - 1]);
    }
    k - d
}

pub mod utils {
    use super::*;

    pub struct CpReader<R: BufRead> {
        r: R,
        b: Vec<u8>,
    }
    impl<R: BufRead> CpReader<R> {
        pub fn new(r: R) -> Self {
            CpReader {
                r: r,
                b: Vec::new(),
            }
        }
        pub fn read_word(&mut self) -> &[u8] {
            self.b.clear();
            let mut consume = 0;
            loop {
                self.r.consume(consume);
                let b = self.r.fill_buf().unwrap();
                assert!(b.len() != 0);
                if let Some(p) = b.iter().position(|&x| x == b' ' || x == b'\n') {
                    self.b.extend_from_slice(&b[..p]);
                    consume = p + 1;
                    break;
                }
                self.b.extend_from_slice(b);
                consume = b.len();
            }
            self.r.consume(consume);
            &self.b
        }
        pub fn read_word_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_word()) }
        }

        pub fn read_line(&mut self) -> &[u8] {
            self.b.clear();
            self.r.read_until(b'\n', &mut self.b).unwrap();
            if self.b.last() == Some(&b'\n') {
                &self.b[..self.b.len() - 1]
            } else {
                &self.b
            }
        }
        pub fn read_line_str(&mut self) -> &str {
            unsafe { std::str::from_utf8_unchecked(self.read_line()) }
        }

        pub fn read<T: CpIn>(&mut self) -> T {
            T::read_from(self)
        }

        pub fn read_vec<T: CpIn>(&mut self, n: usize) -> Vec<T> {
            (0..n).map(|_| self.read()).collect()
        }
        pub fn read_iter<'a, T: CpIn>(&'a mut self, n: usize) -> CpIter<'a, R, T> {
            CpIter {
                r: self,
                n: n,
                _pd: Default::default(),
            }
        }
    }
    pub struct CpIter<'a, R: BufRead + 'a, T> {
        r: &'a mut CpReader<R>,
        n: usize,
        _pd: std::marker::PhantomData<fn() -> T>,
    }
    impl<'a, R: BufRead, T: CpIn> Iterator for CpIter<'a, R, T> {
        type Item = T;
        fn next(&mut self) -> Option<T> {
            if self.n == 0 {
                None
            } else {
                self.n -= 1;
                Some(self.r.read())
            }
        }
    }

    pub trait CpIn {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self;
    }

    impl CpIn for u64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_u64_fast(&mut r.r)
        }
    }
    impl CpIn for i64 {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            read_i64_fast(&mut r.r)
        }
    }
    impl CpIn for char {
        fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
            let b = r.r.fill_buf().unwrap()[0] as char;
            r.r.consume(1);
            let s = r.r.fill_buf().unwrap()[0];
            assert!(s == b' ' || s == b'\n');
            r.r.consume(1);
            b
        }
    }

    macro_rules! cpin_tuple {
        ($($t:ident),*) => {
            impl<$($t: CpIn),*> CpIn for ($($t),*) {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    ($($t::read_from(r)),*)
                }
            }
        };
    }

    macro_rules! cpin_cast {
        ($t_self:ty, $t_read:ty) => {
            impl CpIn for $t_self {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    <$t_read>::read_from(r) as $t_self
                }
            }
        };
    }
    macro_rules! cpin_parse {
        ($t:ty) => {
            impl CpIn for $t {
                fn read_from<R: BufRead>(r: &mut CpReader<R>) -> Self {
                    r.read_word_str().parse().unwrap()
                }
            }
        };
    }
    cpin_cast!(usize, u64);
    cpin_cast!(u32, u64);
    cpin_cast!(u16, u64);
    cpin_cast!(i32, i64);
    cpin_cast!(i16, i64);
    cpin_cast!(i8, i64);

    cpin_parse!(f64);

    cpin_tuple!(T1, T2);
    cpin_tuple!(T1, T2, T3);
    cpin_tuple!(T1, T2, T3, T4);
    cpin_tuple!(T1, T2, T3, T4, T5);

    fn read_u64_fast<R: BufRead>(r: &mut R) -> u64 {
        let mut value = 0;
        loop {
            let mut idx = 0;
            let buf_len;
            {
                let buf = r.fill_buf().unwrap();
                buf_len = buf.len();
                assert!(buf_len != 0);
                while idx < buf_len && b'0' <= buf[idx] && buf[idx] <= b'9' {
                    value = value * 10 + (buf[idx] - b'0') as u64;
                    idx += 1;
                }
            }
            if idx < buf_len {
                r.consume(idx + 1);
                return value;
            }
            r.consume(idx);
        }
    }
    fn read_i64_fast<R: BufRead>(r: &mut R) -> i64 {
        let (consume, sign) = match r.fill_buf().unwrap()[0] {
            b'+' => (true, 1),
            b'-' => (true, -1),
            _ => (false, 1),
        };
        if consume {
            r.consume(1);
        }
        read_u64_fast(r) as i64 * sign
    }
}


use std::io;
use std::cmp;
fn main() {
    let mut s = String::new();
    let mut s2 = String::new();
    io::stdin().read_line(&mut s).unwrap();
    let mut s_spl:Vec<&str> = s.trim().split(' ').collect();
    let k: i32 = s_spl[0].to_string().parse().unwrap();
    let mut max = -1;
    let mut a_first = -1;
    let mut a_old = -1;
    io::stdin().read_line(&mut s2).unwrap();
    for s_loop in s2.trim().split(' ') {
        let a:i32 = s_loop.parse().unwrap();
        if a_old == -1 {
            a_first = a;
        }else {
                max = cmp::max(max, a-a_old);
        }
        a_old = a;
    }
    max = cmp::max(max, k + a_first - a_old);
    println!("{}", k-max);
}


#![allow(unused_macros, deprecated)]

#[allow(dead_code)]
mod utils {
    use std::io::{
        self, BufRead, BufReader, BufWriter, Seek, SeekFrom, Stdin, StdinLock, Stdout, StdoutLock,
        Write,
    };
    use std::mem;
    use std::ops::{Deref, DerefMut};
    use std::ptr;
    use std::slice;
    use std::str::{self, FromStr};

    #[inline]
    fn is_space_or_line_break(b: &u8) -> bool {
        *b == b' ' || *b == b'\n'
    }

    pub struct Scanner<R: BufRead> {
        reader: R,
        buf: Vec<u8>,
    }

    impl<R: BufRead> Scanner<R> {
        #[inline]
        pub fn new(reader: R) -> Scanner<R> {
            Scanner {
                reader: reader,
                buf: Vec::with_capacity(100),
            }
        }

        pub fn read<T: FromStr>(&mut self) -> T {
            self.read_until(is_space_or_line_break);
            self.parse()
        }

        pub fn read2<T1: FromStr, T2: FromStr>(&mut self) -> (T1, T2) {
            (self.read(), self.read())
        }

        pub fn read3<T1: FromStr, T2: FromStr, T3: FromStr>(&mut self) -> (T1, T2, T3) {
            (self.read(), self.read(), self.read())
        }

        pub fn read4<T1: FromStr, T2: FromStr, T3: FromStr, T4: FromStr>(
            &mut self,
        ) -> (T1, T2, T3, T4) {
            (self.read(), self.read(), self.read(), self.read())
        }

        pub fn reads(&mut self) -> &str {
            self.read_until(is_space_or_line_break);
            unsafe { str::from_utf8_unchecked(&self.buf) }
        }

        pub fn readl(&mut self) -> &str {
            self.buf.clear();
            self.reader.read_until(b'\n', &mut self.buf).unwrap();
            let bytes = if self.buf.last() == Some(&b'\n') {
                &self.buf[..self.buf.len() - 1]
            } else {
                &self.buf
            };
            unsafe { str::from_utf8_unchecked(&bytes) }
        }

        pub fn read_vec<T: FromStr>(&mut self, count: usize) -> Vec<T> {
            (0..count).map(|_| self.read()).collect()
        }

        fn read_until<P: FnMut(&u8) -> bool>(&mut self, mut predicate: P) {
            self.buf.clear();
            let mut first = true;

            // https://doc.rust-lang.org/src/std/io/mod.rs.html#1623-1649
            loop {
                let (done, used) = {
                    let available = self.reader.fill_buf().unwrap();
                    if first && available.len() == 0 {
                        panic!("Scan Error (EOF reached)");
                    }

                    match available.iter().position(&mut predicate) {
                        Some(0) if first => (false, 1),
                        Some(i) => {
                            self.buf.extend_from_slice(&available[..i]);
                            (true, i + 1)
                        }
                        None => {
                            self.buf.extend_from_slice(available);
                            (false, available.len())
                        }
                    }
                };

                self.reader.consume(used);
                if done || used == 0 {
                    return;
                }

                first = false;
            }
        }

        #[inline]
        fn parse<T: FromStr>(&mut self) -> T {
            // 文字列をT型へパースする
            let elem = unsafe { str::from_utf8_unchecked(&self.buf) };
            elem.parse()
                .unwrap_or_else(|_| panic!(format!("failed parsing: {}", elem)))
        }
    }

    impl<R: BufRead + Seek> Seek for Scanner<R> {
        #[inline]
        fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
            self.reader.seek(pos)
        }
    }

    pub struct StdinScanner {
        stdin: Stdin,
        scanner: Scanner<BufReader<StdinLock<'static>>>,
    }

    impl StdinScanner {
        #[inline]
        pub fn new() -> StdinScanner {
            let stdin = io::stdin();
            let stdinlock = unsafe { mem::transmute(stdin.lock()) };
            let reader = BufReader::with_capacity(4096, stdinlock);
            let scanner = Scanner::new(reader);
            StdinScanner {
                stdin: stdin,
                scanner: scanner,
            }
        }
    }

    impl Deref for StdinScanner {
        type Target = Scanner<BufReader<StdinLock<'static>>>;

        #[inline]
        fn deref(&self) -> &Self::Target {
            &self.scanner
        }
    }

    impl DerefMut for StdinScanner {
        #[inline]
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.scanner
        }
    }

    pub struct StdoutWriter {
        stdout: Stdout,
        writer: BufWriter<StdoutLock<'static>>,
    }

    impl StdoutWriter {
        #[inline]
        pub fn new() -> StdoutWriter {
            let stdout = io::stdout();
            let stdoutlock = unsafe { mem::transmute(stdout.lock()) };
            let writer = BufWriter::with_capacity(4096, stdoutlock);
            StdoutWriter {
                stdout: stdout,
                writer: writer,
            }
        }

        pub fn write<T: Writable>(&mut self, v: T) {
            v.display(&mut self.writer);
        }

        pub fn writeln<T: Writable>(&mut self, v: T) {
            v.display(&mut self.writer);
            self.writer.write_all(b"\n").unwrap();
        }

        pub fn write_horizontal<I>(&mut self, iter: I)
        where
            I: IntoIterator,
            I::Item: Writable,
        {
            let mut it = iter.into_iter();
            if let Some(elem) = it.next() {
                elem.display(&mut self.writer);
            } else {
                return;
            }

            for elem in it {
                elem.display(&mut self.writer);
                self.writer.write_all(b" ").unwrap();
            }
        }

        pub fn write_vertical<I>(&mut self, iter: I)
        where
            I: IntoIterator,
            I::Item: Writable,
        {
            let mut it = iter.into_iter();
            if let Some(elem) = it.next() {
                elem.display(&mut self.writer);
            } else {
                return;
            }

            for elem in it {
                elem.display(&mut self.writer);
                self.writer.write_all(b"\n").unwrap();
            }
        }
    }

    impl Write for StdoutWriter {
        #[inline]
        fn flush(&mut self) -> io::Result<()> {
            self.writer.flush()
        }

        #[inline]
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.writer.write(buf)
        }
    }

    static DEC_DIGITS_LUT: &'static [u8; 200] = b"0001020304050607080910111213141516171819\
            2021222324252627282930313233343536373839\
            4041424344454647484950515253545556575859\
            6061626364656667686970717273747576777879\
            8081828384858687888990919293949596979899";

    fn write_int<W: Write>(mut writer: W, mut n: u64, is_negative: bool) {
        unsafe {
            let mut buf: [u8; 39] = mem::uninitialized();
            let buf_ptr_start = buf.as_mut_ptr().offset(39);
            let mut buf_ptr = buf_ptr_start;
            let lut_ptr = DEC_DIGITS_LUT.as_ptr();

            while n >= 10000 {
                let rem = (n % 10000) as isize;
                n /= 10000;

                let d1 = (rem / 100) << 1;
                let d2 = (rem % 100) << 1;
                buf_ptr = buf_ptr.offset(-4);
                ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr, 2);
                ptr::copy_nonoverlapping(lut_ptr.offset(d2), buf_ptr.offset(2), 2);
            }

            let mut n = n as isize; // possibly reduce 64bit math

            // decode 2 more chars, if > 2 chars
            if n >= 100 {
                let d1 = (n % 100) << 1;
                n /= 100;
                buf_ptr = buf_ptr.offset(-2);
                ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr, 2);
            }

            // decode last 1 or 2 chars
            if n < 10 {
                buf_ptr = buf_ptr.offset(-1);
                *buf_ptr = (n as u8) + b'0';
            } else {
                let d1 = n << 1;
                buf_ptr = buf_ptr.offset(-2);
                ptr::copy_nonoverlapping(lut_ptr.offset(d1), buf_ptr, 2);
            }

            if is_negative {
                buf_ptr = buf_ptr.offset(-1);
                *buf_ptr = b'-';
            }

            let buf_slice =
                slice::from_raw_parts(buf_ptr, buf_ptr_start as usize - buf_ptr as usize);

            writer.write_all(buf_slice).unwrap();
        }
    }

    pub trait Writable {
        fn display<W: Write>(&self, writer: &mut W);
    }

    impl Writable for str {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            writer.write_all(self.as_bytes()).unwrap()
        }
    }

    impl<'a> Writable for &'a str {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            writer.write_all(self.as_bytes()).unwrap()
        }
    }

    impl Writable for String {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            writer.write_all(self.as_bytes()).unwrap()
        }
    }

    impl Writable for bool {
        #[inline]
        fn display<W: Write>(&self, writer: &mut W) {
            let s: &'static [u8] = if *self { b"Yes" } else { b"No" };
            writer.write_all(s).unwrap();
        }
    }

    macro_rules! impl_writable_int {
        ($($int:ty)*) => {
            $(
                impl Writable for $int {
                    #[allow(unused_comparisons)]
                    fn display<W: Write>(&self, writer: &mut W) {
                        let is_negative = !(*self >= 0);
                        let abs = if is_negative {
                            (!*self as u64).wrapping_add(1)
                        } else {
                            *self as u64
                        };
                        write_int(writer, abs, is_negative);
                    }
                }
            )*
        };
    }

    macro_rules! impl_writable_float {
        ($($float:ty)*) => {
            $(
                impl Writable for $float {
                    #[inline]
                    fn display<W: Write>(&self, writer: &mut W) {
                        write!(writer, "{}", *self).unwrap();
                    }
                }
            )*
        }
    }

    impl_writable_int!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
    impl_writable_float!(f32 f64);

    pub static mut SCANNER: *mut StdinScanner = 0 as *mut StdinScanner;
    pub static mut WRITER: *mut StdoutWriter = 0 as *mut StdoutWriter;

    #[inline]
    pub fn atcoder_initialize() {
        unsafe {
            SCANNER = mem::transmute(Box::new(StdinScanner::new()));
            WRITER = mem::transmute(Box::new(StdoutWriter::new()));
        }
    }

    #[inline]
    pub fn atcoder_finish() {
        unsafe {
            (*WRITER).flush().unwrap();
        }
    }
}

macro_rules! input {
    () => {};
    (@scanner $scanner:ident, @pred [ $($pred:tt)* ], ($var1:tt, $var2:tt) : [($t1:tt, $t2:tt) ; $len:expr]) => {
        let mut $var1 = Vec::with_capacity($len as usize);
        let mut $var2 = Vec::with_capacity($len as usize);

        for _ in 0..$len {
            $var1.push(scan!($scanner, $t1));
            $var2.push(scan!($scanner, $t2));
        }
    };
    (@scanner $scanner:ident, @pred [ $($pred:tt)* ], $var:tt : $t:tt) => {
        let $($pred)* $var = scan!($scanner, $t);
    };
    (@scanner $scanner:ident,) => {};
    (@scanner $scanner:ident, $var:tt : $t:tt) => {
        input!(@scanner $scanner, @pred [], $var : $t);
    };
    (@scanner $scanner:ident, mut $var:tt : $t:tt) => {
        input!(@scanner $scanner, @pred [mut], $var : $t);
    };
    (@scanner $scanner:ident, $var:tt : $t:tt, $($r:tt)*) => {
        input!(@scanner $scanner, $var : $t);
        input!(@scanner $scanner, $($r)*);
    };
    (@scanner $scanner:ident, mut $var:tt : $t:tt, $($r:tt)*) => {
        input!(@scanner $scanner, mut $var : $t);
        input!(@scanner $scanner, $($r)*);
    };
    ($($r:tt)*) => {
        let scanner_ref = unsafe { &mut *$crate::utils::SCANNER };
        input!(@scanner scanner_ref, $($r)*);
    }
}

macro_rules! scan {
    ($scanner:ident, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| scan!($scanner, $t)).collect::<Vec<_>>()
    };
    ($scanner:ident, usize1) => {
        scan!($scanner, usize) - 1
    };
    ($scanner:ident, line) => {
        $scanner.readl().to_string()
    };
    ($scanner:ident, $t:ty) => {
        $scanner.read::<$t>()
    };
}

macro_rules! pprint {
    ($value:expr) => {
        unsafe {
            (*$crate::utils::WRITER).write($value);
        }
    };
    ($value:expr, $($r:tt)*) => {
        let writer = unsafe { &mut *$crate::utils::WRITER };
        writer.write($value);
        writer.write(" ");
        pprint!($($r)*);
    };
}

macro_rules! pprintln {
    ($value:expr) => {
        unsafe {
            (*$crate::utils::WRITER).writeln($value);
        }
    };
    ($value:expr, $($r:tt)*) => {
        let writer = unsafe { &mut *$crate::utils::WRITER };
        writer.write($value);
        writer.write(" ");
        pprintln!($($r)*);
    };
}

macro_rules! atcoder_main {
    ($func:ident) => {
        fn main() {
            $crate::utils::atcoder_initialize();
            $func();
            $crate::utils::atcoder_finish();
        }
    };
}

use std::cmp;

fn run() {
    input! {
        k: u64,
        n: usize,
        mut a: [u64; n]
    }

    a.sort();
    let mut max_distance = a[0] + k - a[n - 1];
    for ai in a.windows(2) {
        let distance = ai[1] - ai[0];
        if distance > max_distance {
            max_distance = distance;
        }
    }

    let ans = k - max_distance;
    pprintln!(ans);
}

atcoder_main!(run);


use proconio::{fastout, input, marker::*};

#[fastout]
fn main() {
    input! {
        k: isize,
        n: usize,
        a: [isize; n],
    }
    let mut ans = 1_000_000_000;
    let mut dp = vec![vec![0; n]; n];

    for i in 0..n {
        let mut dist = 0;
        let mut j = i;
        for x in i+1..n+i {
            let z = if n <= x { x - n } else { x };
            if dp[j][z] == 0 {
                let az = if n == x { k } else { a[z] };
                dp[j][z] = isize::abs(a[j] - az);
            }
            dist += dp[j][z];
            j = z;
        }
        ans = std::cmp::min(ans, dist);
    }

    println!("{}", ans);
}


use proconio::{fastout, input, marker::*};

#[fastout]
fn main() {
    input! {
        k: isize,
        n: usize,
        a: [isize; n],
    }
    let mut ans = 1_000_000_000;

    for i in 0..n {
        let mut dist = 0;
        let mut j = i;
        for x in i+1..n+i {
            let z = if n <= x { x - n } else { x };
            let az = if n == x { k } else { a[z] };
            dist += isize::abs(a[j] - az);
            j = z;
        }
        ans = std::cmp::min(ans, dist);
    }

    println!("{}", ans);
}


use proconio::{input, fastout};

#[fastout]
fn main() {
    input! {
        k: usize, n: usize,
        arr: [usize; n],
    }

    let mut a = arr.clone();
    a.sort();
    let dist = a[n-1] - a[0];
    if n == 2 {
        println!("{}", std::cmp::min(dist, k-dist))
    } else {
        println!("{}", dist)
    }
}


// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func main() {
    let kn = readInts()
    let (k, n) = (kn[0],kn[1])
    let aryN = readInts()
    var ans = aryN[0] - aryN[n - 1] + k
    for i in 0..<n - 1 {
        ans = max(ans, aryN[i + 1] - aryN[i])
    }

    print(k - ans)
}

main()


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let array = readLine()!.componentsSeparatedByString(" ").map{ Int($0)! }
var N = 0
var maxDis = 0
for e in array{
  let dist = e - N
  if(dist > maxDis){
    maxDis = dist
  }
  N = e
}
let around = Int(input[0])!
if(around - N + array[0] > maxDis){
  maxDis = around - N + array[0]
}
print(around - maxDis)


import Foundation

let kn = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
let k = kn[0]
let n = kn[1]

var inputA = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
var minus:[Int] = inputA.map({
    if $0 > 10 {
        return $0 - 20
    } else {
        return $0
    }
})
let plusAns = inputA.maxElement()!-inputA.minElement()!
let minusAns = minus.maxElement()!-minus.minElement()!
print(min(plusAns, minusAns))


import Foundation

let kn = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
let k = kn[0]
let n = kn[1]

var inputA = readLine()!.componentsSeparatedByString(" ").map({ Int($0)!})
inputA = inputA.map({
    if $0 > 10 {
        return $0 - 20
    } else {
        return $0
    }
})
inputA = inputA.sort{ $0 < $1 }
print(inputA.last! - inputA.first!)


import Foundation

let input = readLine()!.componentsSeparatedByString(" ")
let array = readLine()!.componentsSeparatedByString(" ").map{ Int($0)! }
var N = 0
var maxDis = 0
for e in array{
  let dist = e - N
  if(dist > maxDis){
    maxDis = dist
  }
  N = e
}
let around = Int(input[0])!
if(around - N + array[0] > maxDis){
  maxDis = around - N + array[0]
}
print(maxDis)


import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var k: number = 0;
    var n: number = 0;
    var an: number[] = [];
    var ans: number = 0;
    // init
    [k, n] = input.shift().split(" ").map(x => Number(x));
    an = input.shift().split(" ").map(x => Number(x));
    // solve
    var max = 0;
    for (var nx = 0; nx < n; nx++) {
        if (nx < n - 1) {
            max = Math.max(max, an[nx + 1] - an[nx]);
        } else {
            max = Math.max(max, k + an[0] - an[nx]);
        }
    }
    ans = k - max;
    // answer
    console.log(ans);
}

// graph lib
/*
function GRAPH_enumPattern(cur: number[], pat: number[][]): number[][] {
    var arr = [];
    for (var patx = 0; patx < pat.length; patx++) {
        var pos = [cur[0] + pat[patx][0], cur[1] + pat[patx][1]];
        arr.push(pos);
    }
    return arr;
}
*/

// math lib
/*
function Math_max(arr: number[]): number { return arr.reduce((x, y) => Math.max(x, y)); }
function Math_min(arr: number[]): number { return arr.reduce((x, y) => Math.min(x, y)); }
function Math_gcd(): number {
    var ans = arguments[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < arguments.length; i++) {
        ans = f(ans, arguments[i]);
    }
    return ans
};
function Math_gcdArray(values: number[]): number {
    var ans = values[0];
    var f = (a: number, b: number): number => b ? f(b, a % b) : a
    for (var i = 1; i < values.length; i++) {
        ans = f(ans, values[i]);
    }
    return ans
};
function Math_lcm(): number {
    var a = arguments
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_lcmArray(values: number[]): number {
    var a = values
    var g = (n: number, m: number): number => m ? g(m, n % m) : n
    var l = (n: number, m: number): number => n * m / g(n, m)
    var ans = a[0]
    for (var i = 1; i < a.length; i++) {
        ans = l(ans, a[i])
    }
    return ans
}
function Math_primeList(value: number): number[] {
    var ans = [];
    var arr = new Array(value).fill(0);
    for (var i = 2; i < value; i++) {
        if (arr[i] == 0) {
            for (var j = i; j < value; j += i) {
                if (arr[j] == 0) arr[j] = i;
            }
        }
    }
    for (var i = 2; i < value; i++) {
        if (arr[i] == i) ans.push(i);
    }
    return ans;
}
function Math_primeFactor(p: number[], value: number): number[][] {
    var ans: number[][] = [];
    var valmax = value / 2;;
    for (var i = 0; i < p.length; i++) {
        var prime = p[i];
        if (valmax < prime) break;
        var count = 0;
        while (value % prime == 0) {
            value /= prime;
            count++;
        }
        if (count != 0) {
            ans.push([prime, count]);
        }
        if (value == 1) break;
    }
    return ans;
}
*/

// union-find lib
/*
var g_uf_root: number[];
var g_uf_count: number[];
function UF_initRoot(num: number) {
    g_uf_root = new Array(num).fill(-1);
    g_uf_count = new Array(num).fill(1);
}
function UF_getRoot(index: number) {
    if (g_uf_root[index] < 0) {
        return index;
    } else {
        var work0: number = UF_getRoot(g_uf_root[index]);
        g_uf_root[index] = work0;
        return work0
    }
}
function UF_mergeRoot(a: number, b: number) {
    var root0: number = UF_getRoot(a);
    var root1: number = UF_getRoot(b);
    if (root0 == root1) return;
    if (root0 > root1) [root0, root1] = [root1, root0];
    g_uf_count[root0] += g_uf_count[root1];
    g_uf_count[root1] = 0;
    g_uf_root[root1] = root0;
}
*/

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


import * as fs from 'fs';

// main
function main(input: string[]) {
    // param
    var k: number = 0;
    var n: number = 0;
    var an: number[] = [];
    var ans: number = 0;
    // init
    [k, n] = input.shift().split(" ").map(x => Number(x));
    an = input.shift().split(" ").map(x => Number(x));
    // solve
    var max = 0;
    for (var nx = 0; nx < n; nx++) {
        if (nx < n - 1) {
            max = Math.max(max, an[nx + 1] - an[nx]);
        } else {
            max = Math.max(max, k + an[0] - an[nx]);
        }
    }
    ans = k - max;
    // answer
    console.log(ans);
}

// entrypoint
function entrypoint() {
    try {
        // linux
        var input = fs.readFileSync("/dev/stdin", "utf8").trim().split("\n");
        console.debug = function () { };
        main(input);
    }
    catch (ex) {
        // windows
        const lines: string[] = [];
        // @ts-ignore
        const reader = require('readline').createInterface({
            // @ts-ignore
            input: process.stdin,
            // @ts-ignore
            output: process.stdout
        });
        reader.on('line', function (line: string) {
            lines.push(line);
        });
        reader.on('close', function () {
            input = lines;
            main(input);
        });
    }
}
entrypoint();


export class Main {
  static main(input: string): string {
    const tmp: string[] = input.split("\n");
    const [k, n]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const a: number[] = tmp.shift().split(" ").map(int => int - 0);
    let m = 0;
    for (let i = 0; i < n; i++) {
      if (i < n - 1 && a[i + 1] - a[i] > m) {
        m = a[i + 1] - a[i];
      } else if (i == n - 1 && a[0] + (k - a[i]) > m) {
        m = a[0] + (k - a[i]);
      }
    }
    return `${k - m}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', chunk => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const lake = Number(inputs[0].split(' ')[0]);
  const distance = inputs[1].split(' ').map(Number);
  let max = 0;
  let sum = 0;

  for (let i = 1; i < distance.length; i++) {
    sum += distance[i] - distance[i - 1];

    if (max < distance[i] - distance[i - 1]) {
      max = distance[i] - distance[i - 1];
    }
  }

  if (sum > lake / 2) {
    sum = sum - max + (lake - distance[distance.length - 1]) + distance[0];
  }

  console.log(sum);
}


process.stdin.resume();
process.stdin.setEncoding('utf8');

// 標準入力取込
let gInput = '';
process.stdin.on('data', chunk => (gInput += chunk));
process.stdin.on('end', () => main(gInput.split(/\r?\n/)));

// 解答
function main(inputs: string[]): void {
  const lake = Number(inputs[0].split(' ')[0]);
  const distance = inputs[1].split(' ').map(Number);
  let max = distance[distance.length - 1] - distance[distance.length - 2];
  let sum = 0;

  for (let i = 1; i < distance.length; i++) {
    sum += distance[i] - distance[i - 1];
  }

  if (sum > lake / 2) {
    sum = sum - max + (lake - distance[distance.length - 1]) + distance[0];
  }

  console.log(sum);
}


n = int(input())
s = input()

ans = 0
x = 0
for _ in s:
    if _ == 'I':
        x += 1
    else:
        x -= 1
    ans = max(ans, x)

print(ans)


n = int(input())
s = list(input())
x = 0
xmax = 0
for ss in s:
    if ss == "I":
        x += 1
    else:
        x -= 1
    xmax = max(xmax, x)
print(xmax)


N = int(input())
S = input()

max_n = 0
n = 0
for s in S:
  if s == "I":
    n += 1
    if n > max_n:
      max_n = n
  else:
    n -= 1

print(max_n)


 = int(input())
s = input()
x = 0
l = [0]
for a in s:
    if a == "I":
        x = x + 1
        l.append(x)
    else:
        x = x - 1
        l.append(x)

print(max(l))