program example

	implicit none

	integer :: K,N,i,j,count=0,c,d,e,f
    integer,allocatable :: A(:),wa(:)
    
    read(*,*) K,N
    
    allocate(A(0:N+1),wa(N))
    
    read(*,*) A(1:N)

!    write(*,*) A

    A(0)=A(N)
    A(N+1)=A(1)
    
    do j=1,N

        wa(j)=0
        i=j

!        write(*,*) i
        if(i==1) then
            c=A(i+1)-A(i)
            d=A(N+1)-A(N)+K
        else if (i==N) then
            c=A(N+1)-A(N)+K
            d=A(i)-A(i-1)
        else
            c=A(i+1)-A(i)
            d=A(i)-A(i-1)
        end if

        e=A(N+1)-A(N)+K

!        write(*,*) e
!                if(i==1) then
!    			    c=A(i+1)-A(i)
!        		    d=A(i)-A(i-1)+K
!                else if (i==N) then
!     			    c=A(i+1)-A(i)+K
!        		    d=A(i)-A(i-i)  
!                else
!            	    c=A(i+1)-A(i)
!                    d=A(i)-A(i-1)
!                end i
 
        if(c>d) then
            do 
                if (count>=N-1) then
                    count=0
                    exit
                end if

                if(i<=1) then
                    wa(j)=wa(j)+e
                	i=N-1
!                    write(*,*) wa(j)
                else
                    wa(j)=wa(j)+A(i)-A(i-1)
          	        i=i-1
!                    write(*,*) "a:",wa(j)
                end if
                count=count+1
            end do
       	else
            do
                if (count>=N-1) then
                    count=0
                    exit
                end if

                if (i>=N) then
                    wa(j)=wa(j)+e
!                    write(*,*) "b:",wa(j)
                    i=2
                else
                    wa(j)=wa(j)+(A(i+1)-A(i))
!                    write(*,*) wa(j)
                	i=i+1
                end if
                count=count+1
            end do
        end if

        count=0

    end do

    write(*,*) minval(wa)
end program example
