program example

    implicit none

    integer :: K,N,i
    integer,allocatable :: A(:),wa(:),sa(:)

    read(*,*) K,N

    allocate(A(N),wa(N),sa(N))

    read(*,*) A(:)

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

    do i=1,N-1

        sa(i)=A(i+1)-A(i)

    end do

    write(*,*) sum(sa)-maxval(sa)

end program example
