jiahuimbzuai/CoQuIR huggingface dataset:
//  [java]
import java.io.*;
import java.util.*;
class Main{
	static final long MOD = 1_000_000_007; // 10^9+7
    static final int MAX = 2_147_483_646; // intMax 
    static final int INF = 1_000_000_000; // 10^9  
    public static void main(String[] args) throws Exception {
		hayami saori = new hayami();
		int N = saori.saori_hayami();
		int x = saori.saori_hayami();
		int[] a = new int[N];
		for(int i = 0;i < N;i++){
			a[i] = saori.saori_hayami();
		}
		Arrays.sort(a);
		int ans = 0;
		for(int i = 0;i < a.length;i++){
			x -= a[i];
			if(x < 0){
				break;
			}
			ans++;
		}
		if(x > 0 && ans != 0){
			ans--;
		}
		System.out.println(ans);
		
		saori.close();
    }
}

class hayami implements Closeable {
	private final InputStream in = System.in;
	private final byte[] hayami = new byte[1024];
	private int Hayami = 0;
	private int saori = 0;
	private boolean HayamiSaori() {
		if (Hayami < saori) {
			return true;
		}else{
			Hayami = 0;
			try {
				saori = in.read(hayami);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (saori <= 0) {
				return false;
			}
		}
		return true;
	}
	private int SaoriHayami() { 
		if (HayamiSaori()) {
            return hayami[Hayami++];
         }else{
             return -1;
         }
	}
	private static boolean hayami_saori(int hayami) { 
		return 33 <= hayami && hayami <= 126;
	}
	public boolean hayamisaori() { 
		while(HayamiSaori() && !hayami_saori(hayami[Hayami])) Hayami++; return HayamiSaori();
	}
	public String nextHayami() {
		if (!hayamisaori()) throw new NoSuchElementException();
		StringBuilder hayamin = new StringBuilder();
		int saori = SaoriHayami();
		while(hayami_saori(saori)) {
			hayamin.appendCodePoint(saori);
			saori = SaoriHayami();
		}
		return hayamin.toString();
	}
	public long saorihayami() {//nextLong
		if (!hayamisaori()) throw new NoSuchElementException();
		long hayami = 0;
		boolean misao = false;
		int saori = SaoriHayami();
		if (saori == '-') {
			misao = true;
			saori = SaoriHayami();
		}
		if (saori < '0' || '9' < saori) {
			throw new NumberFormatException();
		}
		while(true){
			if ('0' <= saori && saori <= '9') {
				hayami *= 10;
				hayami += saori - '0';
			}else if(saori == -1 || !hayami_saori(saori)){
				return misao ? -hayami : hayami;
			}else{
				throw new NumberFormatException();
			}
			saori = SaoriHayami();
		}
	}
	public int saori_hayami() {//nextInt
		long hayami = saorihayami();
		if (hayami < Integer.MIN_VALUE || hayami > Integer.MAX_VALUE) throw new NumberFormatException();
		return (int) hayami;
	}
	public double Hayamin() { //nextDouble
		return Double.parseDouble(nextHayami());
	}
	public void close() {
		try {
			in.close();
		} catch (IOException e) {
		}
    }
    
}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

// 22
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        long umaibo = sc.nextLong();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
            a[i] = sc.nextInt();

        Arrays.sort(a);
        int i = 0;
        for( ; i < n; i++) {
            umaibo -= a[i];
            if(umaibo < 0) break;
        }

        System.out.println(i);
    }

}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

// 22
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int umaibo = sc.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
            a[i] = sc.nextInt();

        Arrays.sort(a);
        int i = 0;
        for( ; i < n; i++) {
            umaibo -= a[i];
            if(umaibo <= 0) break;
        }

        System.out.println(i);
    }

}
//  [java]
import java.util.Arrays;
import java.util.Scanner;

// 22
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int umaibo = sc.nextInt();
        int[] a = new int[n];
        for(int i = 0; i < n; i++)
            a[i] = sc.nextInt();

        Arrays.sort(a);
        int i = 0;
        for( ; i < n; i++) {
            umaibo -= a[i];
            if(umaibo < 0) break;
        }

        System.out.println(i);
    }

}
//  [cpp]
#include<cstdio>
#include<algorithm>
int main(){
	long long int n,x;
	scanf("%lld%lld",&n,&x);
	long long int a[n]={};
	for(int i=0;i<n;i++){
		scanf("%lld",&a[i]);
	}
	std::sort(a,a+n);
	long long int ans=0;
	for(int i=0;i<n;i++){
		if(a[i]>x){
			break;
		}else{
			ans++;
			x-=a[i];
		}
	}
	if(ans==n && x>0)ans--;
	printf("%lld\n",ans);
	return 0;
}
//  [cpp]
#include <iostream>
#include <algorithm>

using namespace std;



int main()
{
  int N,x;    
  cin >> N >> x;
  int *a = new int[N];
  int ans=0;
  
  for(int i=0;i<N;i++)
  {
      cin >> a[i];
  }
  sort(a,a+N);
  for(int i=0;i<N;i++)
  {
      x=x-a[i];
      if(x<0)
      {
          ans=i;
          break;
      }
      ans+=1;
  }
  if(x>0) ans-=1;
  
 
  cout << ans << endl;
  
   
   
   delete[] a;
   
   return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

int n, m;
vector<int> su;

int main(){
  scanf("%d%d", &n, &m);
  for(int i=0;i<n;i++){
    int suu; scanf("%d", &suu);
    su.push_back(suu);
  }
  sort(su.begin(), su.end());
  for(int i=0;i<n;i++){
    if(m < su[i]){
      printf("%d\n", i);
      return 0;
    }
    m -= su[i];
  }
  printf("%d\n", n - (m > 0));
  return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main(){
  int N,x;
  cin >> N >> x;
  
  int a;
  
  vector<int> v;
  for(int i=0;i<N; i++){
    cin >> a;
    v.push_back(a);
  }
  
  sort(v.begin(), v.end());
  
  int count = 0;
  
  for(int i=0; i<N; i++){
    if(x >= v.at(i) ){
      x -= v.at(i);
      count++;
    }else{
      break;
    }
  }
  
  cout << count << endl;
}
//  [c]

#pragma warning(disable:4996)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>

#pragma region 定義
#define i_cin(X) scanf("%d", &X)
#define i_cin2(X,Y) scanf("%d %d",&X,&Y)
#define i_cin4(X,Y,Z,W) scanf("%d %d %d %d",&X,&Y,&Z,&W)
#define i_cin3(X,Y,Z) scanf("%d %d %d",&X,&Y,&Z)
#define l_cin(X) scanf("%ld",&X)
#define f_cin(X) scanf("%f",&X)
#define l_cin2(X,Y) scanf("%ld %ld",&X,&Y)
#define s_cin(X) scanf("%s",&X)

#define  i_cout(X) printf("%d\n",X)
#define  f_cout(X) printf("%g\n",X)
#define  i_cout2(X,Y) printf("%d %d\n",X,Y)
#define  l_cout(X) printf("%ld\n",X)
#define  s_cout(X) printf("%s\n",X)
#define  ll_cout(X) printf("%lld\n",X)

typedef long long  ll;
#define rept(x, s, n) for (int x = s; x < n; x++)

#define S_RTN(S)  s_cout(S);return 0


#define _itoa(A,N) sprintf(A, "%d", N);

int i_cins(int n, int* A);
int l_cins2(int n, long* A, long* B);
int s_dsort(const void* a, const void* b);
int s_asort(const void* a, const void* b);

int  _gcd(int a, int b);
int  _swp(int* a, int* b);
int _cknum(char* a, int n);
int _atoi(char* s, int len);


int s_asorts(const void* a, const void* b);

//昇順
int s_asorts(const void* a, const void* b) {
	return(strcmp((char*)a, (char*)b));
}
int s_dsort(const void* a, const void* b) {
	return(*(int*)b - *(int*)a);
}
int s_asort(const void* a, const void* b) {
	return(*(int*)a - *(int*)b);
}
int l_cins2(int n, long* a, long* b) {
	int i;
	rept(i, 0, n) {
		l_cin2(*(a + i), *(b + i));
	}
	return 0;
}
int i_cins(int n, int* a) {
	int i;
	for (i = 0; i < n; i++) {
		i_cin(*(a + i));
	}

	return 0;
}
int _gcd(int a, int b) {
	int r, tmp;
	if (a < b) { tmp = a; a = b; b = tmp; }
	r = a % b;
	while (r) {
		if (!r) break;
		a = b; b = r;
		r = a % b;
	}
	return(b);
}

long _max(long a, long b) {
	return a > b ? a : b;
}
long _min(long a, long b) {
	return a < b ? a : b;
}
int _swp(int* a, int* b)
{
	int tmp;
	tmp = *b; *b = *a; *a = tmp;
	return 0;
}

int _cknum(char* a, int n) {
	int i;
	char t = '0';

	for (i = 0; i < n; i++) {
		if (a[i] < '0' || a[i]>'9') return 1;
	}
	return 0;
}


int _atoi(char* s, int len) {
	char tmp[20];
	memcpy(tmp, s, len);
	tmp[len] = 0x00;
	return (atoi(tmp));
}
#pragma endregion


#include <stdio.h>

#include<stdio.h>

int main(void)
{
	int  i, cnt = 0;
	int  x,a[101],n;

	i_cin2(n,x);
	i_cins(n, a);
	qsort(a,n,sizeof(int),s_asort);
	
	for (i = 0; i < n; i++) {
		if (!a[i]) continue;
		cnt++;
		x -= a[i];
		if (x <= 0)break;
	}
	
	(!x) ? i_cout(cnt) : i_cout(cnt - 1);
	return 0;
}
//  [c]
#include<stdio.h>
int main(){
  int N;
  long int x;
  scanf("%d%ld",&N,&x);
  int i,j;
  unsigned int a[N];
  for(i=0;i<N;i++){
    scanf("%ld",&a[i]);
  }
  long int tmp;
  for(i=0;i<N;i++){
    for(j=i+1;j<N;j++){
      if(a[i]>a[j]){
        tmp=a[i];
        a[i]=a[j];
        a[j]=tmp;
      }
    }
  }
  int count=0;
  i=0;
  while(x>0&&a[i]!=0){
    x=x-a[i];
    //printf("%d ",x);
    i++;
    count++;
  }
  if(x!=0){
    printf("%d",count-1);
  }
  else{
    printf("%d",count);
  }
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int cmpint(const void *x, const void *y) {
	return *(int *)x - *(int *)y;
}
int main() {
	int n, x, a[100], sum = 0;
	scanf("%d%d", &n, &x);
	for (int i = 0; i < n; i++) {
		scanf("%d", &a[i]);
	}
	qsort(a, n, sizeof(int), cmpint);
	for (int i = 0; i < n; i++) {
		sum += a[i];
		if (sum > x) {
			printf("%d\n", i);
			return 0;
		}
	}
	printf("%d\n", sum == x ? n : n - 1);
	return 0;
}
//  [c]

    return aNum - bNum;
}
int main(void){
  int n, x;
  int a[105];
  scanf("%d %d", &n,&x);
  
  //int sum = 0;
  for(int i=0;i<n;i++){
    scanf("%d", &a[i]);
    //sum+=a[i];
  }
  /*
  if(x>sum){
    printf("%d", n-1); 
    return 0;
  }
  */
  
  
  qsort(a, n, sizeof(int), compareInt);
  int i,s=0;int ans=0;
  for(i=0;i<n&&s<=x;i++){
    s+=a[i];
  }
    if(s==x && i==n){
      ans = n;     
    }else if(s!=x && i==n){
      ans = n-1;      
    }
  else if(i!=n){
    ans = i-1;
  }
  printf("%d", ans);
  return 0;
}
  
    return aNum - bNum;
}
int main(void){
  int n, x;
  int a[105];
  scanf("%d %d", &n,&x);
  
  //int sum = 0;
  for(int i=0;i<n;i++){
    scanf("%d", &a[i]);
    //sum+=a[i];
  }
  /*
  if(x>sum){
    printf("%d", n-1); 
    return 0;
  }
  */
  
  
  qsort(a, n, sizeof(int), compareInt);
  int i,s=0;int ans=0;
  for(i=0;i<n&&s<=x;i++){
    s+=a[i];
  }
    if(s==x && i==n){
      ans = n;     
    }else if(s!=x && i==n){
      ans = n-1;      
    }
  else if(i!=n){
    ans = i-1;
  }
  printf("%d", ans);
  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int compareInt(const void* a, const void* b)
{
    int aNum = *(int*)a;
    int bNum = *(int*)b;

    return aNum - bNum;
}
int main(void){
  int n, x;
  int a[105];
  scanf("%d %d", &n,&x);
  /*
  int sum = 0;
  for(int i=0;i<n;i++){
    scanf("%d", &a[i]);
    sum+=a[i];
  }
  if(x>sum){
    printf("%d", n-1); 
    return 0;
  }
  */
  
  
  qsort(a, n, sizeof(int), compareInt);
  int i,s=0;int ans=0;
  for(i=0;i<n&&s<=x;i++){
    s+=a[i];
  }
    if(s==x && i==n){
      ans = i;
      
    }else if(s!=x && i==n){
      ans = i-1;
      
    }
  else if(i!=n){
    ans = i-1;
  }
  printf("%d", ans);
  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
int compareInt(const void* a, const void* b)
{
    int aNum = *(int*)a;
    int bNum = *(int*)b;

    return aNum - bNum;
}
int main(void){
  int n, x;
  int a[105];
  scanf("%d %d", &n,&x);
  for(int i=0;i<n;i++){
    scanf("%d", &a[i]);
  }
  
  qsort(a, n, sizeof(int), compareInt);
  int sum=0;int ans=0;
  for(int i=0;i<n;i++){
    sum+=a[i];
    if(sum==x && (sum+a[i+1])>x){
      ans = i+1;
      break;
    }else if(sum<x && (sum+a[i+1])>x){
      ans = i;
      break;
    }
  }
  printf("%d", ans);
  return 0;
}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {


  var inp = input.split('\n');

  var buf = inp[0].split(' ');

  var N = parseInt(buf[0]);
  var x = parseInt(buf[1]);

  var an = inp[1].split(' ');

  // 昇順ソート
  an.sort(function (a, b) {
    return a - b;
  })

  var ans = 0;
  for (var i = 0; i < N; i++) {
    if(parseInt(an[i]) <= x){
      x -= parseInt(an[i]);
      ans++;
    }else{
      break;
    }
    if(i === N - 1){
      if(x !== 0) ans--;
    }
  }

  console.log('%d', ans);

}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var N = parseInt(input[0].split(" ")[0]);
  var x = parseInt(input[0].split(" ")[1]);
  a = new Array(N);
  tmp = input[1].split(" ");
  var sum =0;
  for(i=0;i<N;i++){
	  a[i]=parseInt(tmp[i]);
	sum+=a[i];
  }
  var num=x;
  a.sort(function(a,b){return a-b});
  var ans =0;
  for(i=0;i<N;i++){
	  if(x>=a[i]){
		ans++;
		x-=a[i];
	  }else{
		  break;
	  }
  }
  if(num>sum){
	  ans=N-1;
  }
  console.log('%s', ans);
}
  
// "実行する"ボタンを押した時に実行される関数 (デバッグ用)
function debug(){
  var input = document.getElementById("input").value;
  Main(input);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";

const main = arg => {
  arg = arg.trim().split("\n");
  const N = parseInt(arg[0].split(" ")[0]);
  let x = parseInt(arg[0].split(" ")[1]);
  let a = new Array(N);
  let tmp = arg[1].split(" ");
  let sum =0;
  for(let i=0;i<N;i++){
	  a[i]=parseInt(tmp[i]);
	sum+=a[i];
  }
  let num=x;
  a.sort(function(a,b){return a-b});
  
  let ans = 0;
  
  for(let i=0;i<N;i++){
	  if(x>=a[i]){
		ans++;
		x-=a[i];
	  }else{
		  break;
	  }
  }
  
  if(num>sum){
	  ans=N-1;
  }
  console.log(ans);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input) {
  const args = input.split('\n');
  let ary1 = args[0].split(' ').map(n => parseInt(n, 10));
  const N = parseInt(ary1[0], 10);
  let x = parseInt(ary1[1], 10);
  let ary2 = args[1].split(' ').map(n => parseInt(n, 10)).sort();
  let ans = 0;
  
  for (let i = 0; i < N; i++) {
  	if (x >= ary2[i]) {
      ans++;
      x -= ary2[i];
    }
  }
  
  if (x > 0 && ans !== 0) { 
    console.log(ans - 1);
  } else { 
    console.log(ans); 
  }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main(input) {
  const args = input.split('\n');
  const N = parseInt(args[0].split(' ')[0], 10);
  let x = parseInt(args[0].split(' ')[1], 10);
  let ary = args[1].split(' ').map(n => parseInt(n, 10)).sort();
  let ans = 0;
  
  for (let i = 0; i < N; i++) {
  	if (x >= ary[i]) {
      ans++;
      x -= ary[i];
    }
  }
  
 if (x > 0 && ans !== 0) { 
   console.log(ans - 1); 
 } else { console.log(ans); }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
function main(input) {
  const args = input.split('\n');
  const N = parseInt(args[0].split(' ')[0], 10);
  let x = parseInt(args[0].split(' ')[1], 10);
  let ary = args[1].split(' ').map(n => parseInt(n, 10)).sort();
  let ans = 0;
  
  for (let i = 0; i < N; i++) {
  	if (x >= ary[i]) {
      ans++;
      x -= ary[i];
    }
  }
  
 if (x > 0) { console.log(ans - 1); }
 else { console.log(ans); }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [go]
package main

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

//Util
func nextStr() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func maxInt(a, b int) int {
	if a > b {
		return a
	} else {
		return b
	}
}

func minInt(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}

func absInt(a int) int {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func absFloat64(a float64) float64 {
	if a >= 0 {
		return a
	} else {
		return -a
	}
}

func maxFloat64(a, b float64) float64 {
	if a > b {
		return a
	} else {
		return b
	}
}

func minFloat64(a, b float64) float64 {
	if a > b {
		return b
	} else {
		return a
	}
}

func str2Int(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}

func reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	if x == 2 {
		return true
	}
	if x%2 == 0 {
		return false
	}

	b := true
	rootx := int(math.Sqrt(float64(x)))
	i := 3
	for i <= rootx {
		if x%i == 0 {
			b = false
			break
		}
		i += 2
	}
	return b
}

func PrimeFactors(n int) (pfs []int) {
	// Get the number of 2s that divide n
	for n%2 == 0 {
		pfs = append(pfs, 2)
		n = n / 2
	}

	// n must be odd at this point. so we can skip one element
	// (note i = i + 2)
	for i := 3; i*i <= n; i = i + 2 {
		// while i divides n, append i and divide n
		for n%i == 0 {
			pfs = append(pfs, i)
			n = n / i
		}
	}

	// This condition is to handle the case when n is a prime number
	// greater than 2
	if n > 2 {
		pfs = append(pfs, n)
	}

	return
}

//Main
const (
	initialBufSize = 10000
	maxBufSize     = 1000000
	mod            = 1e9 + 7
)

var (
	sc *bufio.Scanner = func() *bufio.Scanner {
		sc := bufio.NewScanner(os.Stdin)
		buf := make([]byte, initialBufSize)
		sc.Buffer(buf, maxBufSize)
		return sc
	}()
)

var N, x int

func main() {
	sc.Split(bufio.ScanWords)
	//X: 最初のマス
	N, x = nextInt(), nextInt()

	a := make([]int, N)
	for i := 0; i < N; i++ {
		a[i] = nextInt()
	}

	sort.Ints(a)
	ans := 0
	j := 0
	for i := 0; i < N; i++ {
		if a[i] <= x {
			ans++
			x -= a[i]
			j = i
			continue
		}
	}
	if x > 0 && j == N-1 {
		ans--
	}

	fmt.Println(maxInt(0, ans))
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func scanInt() int {
	sc.Scan()
	iv, _ := strconv.Atoi(sc.Text())
	return iv
}

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	n, x := scanInt(), scanInt()
	a := make([]int, n)
	for i := range a {
		a[i] = scanInt()
	}
	sort.Ints(a)

	for i := range a {
		x -= a[i]
		if x < 0 {
			fmt.Println(i)
			return
		}
	}
	if x == 0 {
		fmt.Println(n)
	} else {
		fmt.Println(n - 1)
	}
}
//  [go]
package main

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

const mod = 1000000007

// 1MB
const ioBufferSize = 1 * 1024 * 1024

var sc = func() *bufio.Scanner {
	sc := bufio.NewScanner(os.Stdin)
	sc.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	sc.Split(bufio.ScanWords)
	return sc
}()

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func isPrime(a int) bool {
	for j := 2; j*j <= a; j++ {
		if a%j == 0 {
			return false
		}
	}
	return true
}

func main() {
	n, x := nextInt(), nextInt()
	a := make([]int, n)

	for i := 0; i < n; i++ {
		a[i] = nextInt()
	}
	sort.Ints(a)

	s, res := 0, 0
	for i := 0; i < n-1; i++ {
		s += a[i]
		if s <= x {
			res++
		}
	}
	if s+a[n-1] == x {
		res++
	}
	fmt.Println(res)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n, x int
	fmt.Scan(&n, &x)
	as := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&as[i])
	}
	sort.Ints(as)

	ans := 0
	for i := 0; i < n; i++ {
		if as[i] <= x {
			ans++
			x -= as[i]
		}
	}
	if x > 0 {
		ans--
		if ans < 0 {
			ans = 0
		}
	}

	fmt.Println(ans)
}
//  [go]
package main

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

func main() {
	scanInit()

	n := nextInt()
	x := nextInt()
	a := make([]int, n)

	for i := 0; i < n; i++ {
		a[i] = nextInt()
	}
	sort.Ints(a)
	ans := 0
	for i := 0; i < n; i++ {
		if a[i] <= x {
			x -= a[i]
			ans++
		}
	}
	if x != 0 && ans > 0 {
		ans--
	}
	fmt.Println(ans)

}

// ---- readfunc
var sc = bufio.NewScanner(os.Stdin)

func scanInit() {
	const cap = 200 * 1024 // default=64*1024
	var buf = make([]byte, cap)
	sc.Buffer(buf, cap)
	sc.Split(bufio.ScanWords)
	return
}
func nextInt() int {
	sc.Scan()
	i, _ := strconv.Atoi(sc.Text())
	return i
}
func nextStr() string {
	sc.Scan()
	return sc.Text()
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func main() {
	scanInit()

	n := nextInt()
	x := nextInt()
	al := make([]int, n)

	for i := 0; i < n; i++ {
		al[i] = nextInt()
	}
	sort.Ints(al)

	cnt := 0
	for i := 0; i < n; i++ {
		if x >= al[i] {
			x -= al[i]
			cnt++
		} else {
			break
		}
	}
	if x > 0 && cnt > 0 {
		cnt--
	}
	fmt.Println(cnt)

}

// ---- 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()
}
//  [ruby]
N,x = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)
A.sort!
num = 0
A.each do |a|
    if a <= x then
        x -= a
        num += 1
    else
        x -= a
        break
    end
end
num -=1 if x > 0
puts num
//  [ruby]
n,x = gets.split(' ').map(&:to_i)
a = gets.split(' ').map(&:to_i)
count = 0
a.sort!
sum = a.inject(:+)

if sum == x
	count = n
else
	n.times do
		break if x < a[0]
	x = x - a.shift
	count+=1
	end
count = count - 1 if count == n
end

puts count
//  [ruby]
N, X = gets.split.map(&:to_i)
A = gets.split.map(&:to_i).sort
p = 0
r = A.inject(X) do |x, a|
  p += 1 if x - a >= 0
  x - a
end
p -= 1 if r > 0
puts p
//  [ruby]
n, x = gets.chomp.split(' ').map(&:to_i)
list = gets.chomp.split(' ').map(&:to_i).sort

count = 0

n.times do |i|
  x -= list[i]
  if x >= 0
    count += 1
  else
    break;
  end
end

if x > 0
  n.times do |i|
    if x >= 0
      x -= list[i]
      count -= 1
    else
      break;
    end
  end
end

print count
//  [ruby]
N,x=gets.chomp.split(" ").map(&:to_i);
as=gets.chomp.split(" ").map(&:to_i).sort;
cnt = 0
as.each do |a|
    x -= a
    if x < 0
        break
    end
    cnt += 1
end
p cnt
//  [ruby]
n , x = gets.split.map &:to_i
as = gets.split.map &:to_i
as = as.sort

cnt = 0
as.each do |y|
  if y <= x
    x -= y
    cnt += 1
  else
    break
  end
end

p cnt
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let mut s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};

    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };

    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };

    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };

    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };

    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input!{
        n: usize,
        x: u32,
        aa: [u32; n],
    };
    let mut a = aa.clone();
    let mut ans = 0;
    let mut left = x;
    a.sort();

    for b in a {
        if left < b{
            println!("{}", ans);
            return;
        }
        left = left - b;
        ans += 1;
    }
    if left > 0 {
        ans -= 1;
    }
    println!("{}", ans);
}
//  [rust]
use std::str::FromStr;

fn get_one<T : FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().parse().ok().unwrap();
}

fn get_vec<T : FromStr>() -> Vec<T> {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    return s.trim().split_whitespace().map(|e| e.parse().ok().unwrap()).collect();
}

fn get_vec_by_lines<T : FromStr>(n : usize) -> Vec<T> {
    let mut v : Vec<T> = Vec::new();
    for _i in 0..n {
        let x : T = get_one();
        v.push(x);
    }
    return v;
}

fn main() {
    let v : Vec<i64> = get_vec();
    let n = v[0];
    let mut k = v[1];
    let mut a : Vec<i64> = get_vec();
    a.sort();
    let mut ans = 0;
    for x in a {
        if x > k {
            break;
        }
        k -= x;
        ans += 1;
    }
    println!("{}", if k > 0 && ans == n {ans-1} else {ans});
}
//  [rust]
use std::io::Read;

fn main() {
    let mut buf = String::new();
    std::io::stdin().read_to_string(&mut buf).ok();
    let mut it = buf.split_whitespace();
    let n = it.next().unwrap().parse::<usize>().unwrap();
    let mut x = it.next().unwrap().parse::<i32>().unwrap();
    let mut a = (0..n).map(|_| it.next().unwrap().parse::<i32>().unwrap()).collect::<Vec<_>>();
    a.sort();
    let mut res = 0;
    for &t in &a {
        if t <= x {
            x -= t;
            res += 1;
        }
    }
    if res == n && x != 0 { res -= 1; }
    println!("{}", res);
}
//  [rust]
use proconio::input;

fn main() {
    input!{
        n: i64,
        x: i64,
        a: [i64; n],
    }

    let mut x = x;
    let mut a = a;
    let mut b = vec![0 as i64; n as usize];

    a.sort();

    for i in 0..n {
        if x >= a[i as usize] {
            b[i as usize] = a[i as usize];
            x -= a[i as usize];
        }
    }

    let mut ans = 0;

    for i in 0..n {
        if a[i as usize] == b[i as usize] {
            ans += 1;
        }
    }

    if ans > 0 &&  x > 0 {
        ans -= 1;
    }

    println!("{}", ans);
}
//  [rust]
use proconio::input;

fn main() {
    input!{
        n: i64,
        x: i64,
        a: [i64; n],
    }

    let mut x = x;
    let mut a = a;
    let mut b = vec![0; n as usize];

    a.sort();

    for i in 0..n {
        if x >= a[i as usize] {
            b[i as usize] = a[i as usize];
            x -= a[i as usize];
        }
    }

    let mut ans = 0;

    for i in 0..n {
        if a[i as usize] == b[i as usize] {
            ans += 1;
        }
    }

    if ans > 0 &&  x > 0 {
        ans -= 1;
    }

    println!("{}", ans);
}
//  [rust]
use proconio::input;

fn main() {
    input!{
        n: i64,
        x: i32,
        a: [i32; n],
    }

    let mut x = x;
    let mut a = a;
    let mut b = vec![0; n as usize];

    a.sort();

    for i in 0..n {
        if x >= a[i as usize] {
            b[i as usize] = a[i as usize];
            x -= a[i as usize];
        }
    }

    let mut ans = 0;

    for i in 0..n {
        if a[i as usize] == b[i as usize] {
            ans += 1;
        }
    }

    if ans > 0 &&  x > 0 {
        ans -= 1;
    }

    println!("{}", ans);
}
//  [swift]
let input=readLine()!.characters.split(" ").map{Int(String($0))!}
let N=input[0]
var x=input[1]
let a=readLine()!.characters.split(" ").map{Int(String($0))!}.sort()
var ans=N-1
for i in 0..<N {
  x-=a[i]
  if x<=0 {
    ans=i+(x<0 ?0:1)
    break
  }
}
print(ans)
//  [swift]
let input=readLine()!.characters.split(" ").map{Int(String($0))!}
let N=input[0]
var x=input[1]
let a=readLine()!.characters.split(" ").map{Int(String($0))!}.sort()
for i in 0..<N {
  x-=a[i]
  if x<=0 {
    print(i+(x<0 ?0:1))
    break
  }
}
if x>0{print(N-1)}
//  [swift]
import Foundation
var rd = readLine()!.split(separator: " ").map({Int($0)!})
let rdSnack = readLine()!.split(separator: " ").map({Int($0)!}).sorted()

let N = rd[0]
var x = rd[1]
var count = 0

if rdSnack[0] <= x {
 


for i in 0 ..< N {
    
    if x <= 0 {
       
        break
    }
    x -= rdSnack[i]
    
    count += 1
    //print("countがインクリメントされた")
}

if x > 0 {
    print(count - 1)
}else {
print(count)
}
}
else {

    print(0)
}
//  [swift]
import Foundation
var rd = readLine()!.split(separator: " ").map({Int($0)!})
let rdSnack = readLine()!.split(separator: " ").map({Int($0)!}).sorted()

let N = rd[0]
var x = rd[1]
var count = 0

if rdSnack[0] < x {
    


for i in 0 ..< N {
    
    if x < 0 {
       
        break
    }
    x -= rdSnack[i]
    
    count += 1
  //  print("countがインクリメントされた")
}

if x > 0 {
    print(count - 1)
}else {
print(count)
}
}
else {
    print(0)
}
//  [swift]
import Foundation
var rd = readLine()!.split(separator: " ").map({Int($0)!})
let rdSnack = readLine()!.split(separator: " ").map({Int($0)!}).sorted()

let N = rd[0]
var x = rd[1]
var count = 0
for i in 0 ..< N {
    
    if x < 0 {
        print("x<0")
        break
    }
    x -= rdSnack[i]
    
    count += 1
  //  print("countがインクリメントされた")
}
if x > 0 {
    print(count - 1)
}else {
print(count)
}
//  [typescript]
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"));
//  [typescript]
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"));
//  [typescript]
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"));
//  [typescript]
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"));
//  [python]
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()
//  [python]
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)
//  [python]
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)
//  [python]
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))
//  [python]
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))
//  [python]
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))
//  [java]
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;
        }

    }
}
//  [java]
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;
    }
}
//  [java]
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());}
}
//  [cpp]
#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;
}
//  [cpp]
#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();
}
//  [cpp]
#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;

}
//  [cpp]
#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;

}
//  [c]
// 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;
}
//  [c]
#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);
}