use std::collections::HashMap;
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut v = Vec::new();
    let mut map = HashMap::new();
    for _ in 0..n {
        let x:i64 = read();
        v.push(x);
        map.entry(x).and_modify(|e| *e += 1).or_insert(1);
    }
    let mut ans = 0;
    for i in map.values() {
        ans += i * (i -1) / 2;
    }
    for i in v.iter() {
        let val = map[i];
        let before = val * (val - 1) / 2;
        let after = (val - 1) * (val - 2) / 2;
        println!("{}", ans - before + after);
    }
}


use std::collections::HashMap;
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut v = Vec::new();
    let mut map = HashMap::new();
    for _ in 0..n {
        let x:i64 = read();
        v.push(x);
        *map.entry(x).or_insert(0) += 1;
    }
    let mut ans = 0;
    for i in map.values() {
        ans += i * (i -1) / 2;
    }
    for i in v.iter() {
        let val = map[i];
        let before = val * (val - 1) / 2;
        let after = (val - 1) * (val - 2) / 2;
        println!("{}", ans - before + after);
    }
}


use std::collections::HashMap;
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut v = Vec::new();
    let mut map = HashMap::new();
    for _ in 0..n {
        let x:i64 = read();
        v.push(x);
        *map.entry(x).or_insert(0) += 1;
    }
    let mut ans = 0;
    for i in map.values() {
        ans += i * (i -1) / 2;
    }
    for i in v {
        let val = map[&i];
        let before = val * (val - 1) / 2;
        let after = (val - 1) * (val - 2) / 2;
        println!("{}", ans - before + after);
    }
}


import Foundation
let N = Int(String(readLine()!))!
let nums = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
var table: [Int: Int] = [:]
var sum = 0
for n in nums {
  table[n] = (table[n] ?? 0) + 1
}
for (key, value) in table {
  sum += value * (value - 1) / 2
}
for n in nums {
  print(sum - table[n]! + 1)
}


import Foundation

/*
// 1
let N = Int(readLine()!)!

// 1 2
let split = readLine()!.componentsSeparatedByString(" ")
let N = Int(split[0])!
let S = Int(split[1])!

// 1 2 3 4 5
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
*/

let N = Int(readLine()!)!
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
var dic = [Int: Int]()
var answer = 0
for e in array {
  if dic[e] != nil {
    dic[e] = dic[e]! + 1
  } else {
    dic[e] = 1
  }
  answer += dic[e]! - 1
}

for e in array {
  print(answer - dic[e]! + 1 )
}


import Foundation

/*
// 1
let N = Int(readLine()!)!

// 1 2
let split = readLine()!.componentsSeparatedByString(" ")
let N = Int(split[0])!
let S = Int(split[1])!

// 1 2 3 4 5
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
*/

let N = Int(readLine()!)!
let array = readLine()!.componentsSeparatedByString(" ").map { Int($0)! }
var dic = [Int: Int]()
for e in array {
  if dic[e] != nil {
    dic[e] = dic[e]! + 1
  } else {
    dic[e] = 1
  }
}
for e in array {
  var answer = 0
  for f in dic {
    var endIndex = f.1
    if e == f.0 { endIndex -= 1 }
    for g in 0 ..< endIndex {
      answer += g
    }
  }
  print(answer)
}


import * as fs from "fs";

function calcCombination(n: number) {
	return n * (n - 1) / 2;
}

const input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const n = +input[0];
const a = input[1].split(" ").map((x: string): number => +x);

const dict: Array<number> = [];
for (const ball of a) {
	if (dict[ball] === undefined) dict[ball] = 0;
	dict[ball] += 1;
}

// pre-calc
const combinations = new Array(n + 1);
for (const value of dict) {
	if (value === undefined) continue;
	if (combinations[value] === undefined) {
		combinations[value] = calcCombination(value);
	}
	if (combinations[value - 1] === undefined) {
		combinations[value - 1] = calcCombination(value - 1);
	}
}

let all_sum = 0;
for (const value of dict) {
	if(value === undefined) continue;
	all_sum += combinations[value];
}

for (let i = 0; i < n; i++) {
	const count: number = dict[a[i]];
	const ans = all_sum - combinations[count] + combinations[count - 1];
	console.log(ans);
}


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

// 標準入力取込
var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});
process.stdin.on('end', function() {
    main(g_input.split(/\r?\n/));
});

// 解答
function main(inputs:Array<string>) : void {

    // ボールの総数
    const ball: number = Number.parseInt(inputs[0]);
    // ボールに記載されている整数のリスト
    const ballList: number[] = inputs[1].split(" ").map((x: string): number => +x);
    // 各整数のボールの個数
    const numList: number[] = [];
    // 各整数の組み合わせ数
    const combinations = new Array(ball + 1);
    // 全組み合わせ数
    let all_sum = 0;

    // 各整数のボールの個数計算
    for (const ball of ballList) {

        if (numList[ball] === undefined) numList[ball] = 0;
        numList[ball] += 1;
    }

    // 各整数の組み合わせ数計算
    for (const value of numList) {

        if (value === undefined) continue;

        if (combinations[value] === undefined) {

            combinations[value] = calcCombination(value);
        }

        if (combinations[value - 1] === undefined) {

            combinations[value - 1] = calcCombination(value - 1);
        }
    }

    // 全組み合わせ数合算
    for (const value of numList) {

        if(value === undefined) continue;
        all_sum += combinations[value];
    }

    for (let i = 0; i < ball; i++) {

        const count: number = numList[ballList[i]];
        const answer = all_sum - combinations[count] + combinations[count - 1];
        console.log(answer);
    }
}

// 組み合わせ計算
function calcCombination(num: number) {

	return num * (num - 1) / 2;
}


export class Main {
  static main(input: string): void {
    const tmp: string[] = input.split("\n");
    const [n]: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const a: number[] = tmp.shift().split(" ").map(int => parseInt(int));
    const map = {};
    for (let i = 0; i < n; i++) {
      const ai = a[i];
      if (map[ai] == null) {
        map[ai] = 1;
      } else {
        map[ai] = map[ai] + 1;
      }
    }
    const keys = Object.keys(map);
    let all = 0;
    const minusMap = {};
    for (let i = 0, len = keys.length; i < len; i++) {
      const value = map[keys[i]];
      const count = value * (value - 1) / 2;
      all += count;
      minusMap[keys[i]] = count - (value - 1) * (value - 2) / 2;
    }
    for (let i = 0; i < n; i++) {
      console.log(all - minusMap[a[i]]);
    }
  }
}
Main.main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  const inputs =input.split('\n')
  const [N] = inputs[0].split(' ').map(Number)
  const A = inputs[1].split(' ').map(Number)

  const count = []
  for(let i = 0; i < N; i++) {
    if (count[A[i]] === undefined) {
      count[A[i]] = 0
    }
    count[A[i]] = count[A[i]] + 1
    // console.log(count)
  }

  // console.log(count)
  for(let i = 0; i <= N - 1; i++) {
    let num = 0
    for(let j = 1; j <= count.length - 1; j++) {
      if (count[j] === undefined) continue
      const as = A[i] !== j ? count[j] : count[j] - 1
      num += as * ( as - 1 ) / 2
    }
    console.log(num)
  }

}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


import * as fs from 'fs';

namespace AtCoder.abc159 {

    class ProgramD {
        args: string[];

        constructor(args: string[]) {
            this.args = args;
        }

        /**
         * in
         * 5
         * 1 1 2 1 2
         * out
         * 2
         * 2
         * 3
         * 2
         * 3
         */
        main(): void {

            const n: number = parseInt(this.args[0], 10);
            const a: number[] = this.args[1].split(' ').map(Number);

            for (let i = 0; i < n; i++) {

                // const wk: number[] = [];
                // for (let j = 0; j < n; j++) {
                //     if (j !== i) {
                //         wk.push(a[j]);
                //     }
                // }

                let cnt: number = 0;
                for (let i2: number = 0; i2 < n ; i2++) {
                    if (i === i2) continue;
                    for (let j2: number = i2; j2 < n ; j2++) {
                        if (i === j2) continue;
                        if (j2 === i2) continue;
                        if (a[i2] === a[j2]) {
                            cnt++;
                        }
                    }
                }

                console.log(cnt);
            }
        }
    }

    const args = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
    const prg = new ProgramD(args);
    prg.main();
}


const stdin: string[] = [];

function main() {
    const As = stdin[1].split(" ").map(_ => parseInt(_));

    const m: {[index: string]: number} = {};
    As.forEach(A => {
        const a = `${A}`;
        m[a] = m[a] || 0;
        m[a] += 1;
    });
    const keys = Object.keys(m);

    const c: {[index: string]: number} = {};
    const d: {[index: string]: number} = {};
    keys.forEach(i => {
        c[i] = combi(m[i]);
        d[i] = combi(m[i] - 1);
    })

    As.forEach(A => {
        const a = `${A}`;
        const N = m[a] - 1;

        let t = 0;
        keys.filter(_ => a !== _).forEach(_ => t += c[_]);
        t += d[a];

        console.log(t);
    });
}

function fact(n: number) {
    let number = 1;
    for (let i = 1; i <= n; i ++) {
      number *= i;
    }
    return number;
}

function combi(n: number) {
    if (n < 2) {
        return 0;
    }
    return fact(n) / ( fact(2) * fact(n - 2) )
}

require("readline").createInterface({
  input: process.stdin,
  output: process.stdout
}).on("line", _ => {
    stdin.push(_);
}).on("close", () => main());


n = int(input())
li = list(map(int, input().split()))
li = [[li[i], i] for i in range(n)]
li.sort()
count = 0
for i in range(n):
    if count > 2:
        print("NO")
        break
    if li[i][1] != i:
        count+=1
else:
    if count % 2 == 0:
        print("YES")
    else:
        print("NO")


n = int(input())
p = list(map(int,input().split()))
pp = sorted(p)
def f(n,p,pp):
    flag =0
    for i in range(n):
        if p[i] != pp[i]:
            if flag == 2:
                return("NO")
            else:
                flag += 1
    return("YES")
print(f(n,p,pp))


N = int(input())

p = list(map(int,input().split()))
plst = sorted(p)
count = 0
for i in range(N):
	if p[i] != plst[i]:
		count += 1

print("YES" if count <= 2 else "NO")


N = int(input())
p = list(map(int,input().split()))

if p == sorted(p):
    print('YES')
else:
    ret = 'NO'
    # 全通りの組み合わせをみて、昇順かどうか調べる
    for i in range(N-1):
        for j in range(i+1, N):

            # p[i]とp[j]より小さければ抜ける
            if p[i] < p[j]:
                continue
            else:
                k = p.copy()
                k[i], k[j] = k[j], k[i]

            is_sorted = True
            for l in range(N-1):
                if k[l+1] < k[l]:
                    is_sorted = False
                    break

            if is_sorted:
                ret = 'YES'
                break
        if is_sorted:
            break

    print(ret)


N = int(input())
p = list(map(int, input().split()))
ans = 0
for i in range(N):
  if p[i] != i+1:
    ans += 1

if ans <= 2:
  print("YES")
else:
  prin("NO")


n = int(input())
p = list(map(int, input().split()))
cnt = 0

for i in range(0, n-1):
    x = abs(p[i]-p[i+1])
    if x != 1:
        cnt += 1

if cnt < 3:
    print("YES")
else:
    print("NO")


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class Main {

	private final static int MOD = 1000000007;

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int[] p = new int[N];
		sc.fill(p);

		int[] copy = Arrays.copyOf(p, p.length);
		Arrays.sort(copy);
		int count = 0;
		for (int i = 0; i < N; i++) {
			if (p[i] != copy[i]) {
				count++;
			}
		}

		if (count <= 2) {
			System.out.println("YES");
		} else {
			System.out.println("NO");
		}
	}

	public static class Pair {
		private Integer x;
		private Integer y;
		private int hashCode;

		public Pair(Integer x, Integer y) {
			this.x = x;
			this.y = y;
			this.hashCode = x << 16 + y;
		}

		@Override
		public int hashCode() {
			return hashCode;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Pair other = (Pair) obj;
			if (!x.equals(other.x))
				return false;
			if (!y.equals(other.y))
				return false;
			return true;
		}

		@Override
		public String toString() {
			return "[" + x + ", " + y + "]";
		}
	}

	private static boolean isDebug = System.getProperty("sun.desktop") != null;

	private static void debug(Object... o) {
		if (isDebug) {
			System.err.println(Arrays.deepToString(o));
		}
	}

	private static int add(int a, int b) {
		return (a + b) % MOD;
	}

	private static int sub(int a, int b) {
		return (a - b % MOD) % MOD;
	}

	private static int mul(int a, int b) {
		return ((a % MOD) * (b % MOD)) % MOD;
	}

	public static class Scanner {
		private BufferedInputStream inputStream;
		private StringBuilder buffer = new StringBuilder();

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

		public int nextInt() throws IOException {
			int num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(int[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
			}
		}

		public void fill(int[] a, int[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
				b[i] = nextInt();
			}
		}

		public long nextLong() throws IOException {
			long num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(long[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
			}
		}

		public void fill(long[] a, long[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
				b[i] = nextLong();
			}
		}

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

			return array;
		}

		public String next() throws IOException {
			int read = skip();
			do {
				buffer.append((char) read);
			} while ((read = inputStream.read()) > 0x20);

			String text = buffer.toString();
			buffer.delete(0, buffer.length());

			return text;
		}

		private int skip() throws IOException {
			int read;
			while ((read = inputStream.read()) <= 0x20)
				;

			return read;
		}
	}
}


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.StringJoiner;

class Main {

    static PrintWriter out;
    static InputReader sc;

    public static void main(String[] args) {
        sc = new InputReader(System.in);
        out = new PrintWriter(System.out);
        solve();
        out.flush();
    }

    static void solve() {
        int N = sc.nextInt();
        int[] a = sc.nextIntArray(N);
        int cnt = 0;
        for (int i = 0; i < N; i++) {
            if (a[i] != i + 1) {
                cnt++;
            }
        }
        if (cnt > 2) {
            out.println("NO");
        } else {
            out.println("YES");
        }
    }

    static void debug(Object... args) {
        StringJoiner j = new StringJoiner(" ");
        for (Object arg : args) {
            if (arg == null) {
                j.add("null");
            } else if (arg instanceof int[]) {
                j.add(Arrays.toString((int[]) arg));
            } else if (arg instanceof long[]) {
                j.add(Arrays.toString((long[]) arg));
            } else if (arg instanceof double[]) {
                j.add(Arrays.toString((double[]) arg));
            } else if (arg instanceof char[]) {
                j.add(Arrays.toString((char[]) arg));
            } else if (arg instanceof Object[]) {
                j.add(Arrays.toString((Object[]) arg));
            } else {
                j.add(arg.toString());
            }
        }
        System.err.println(j.toString());
    }

    static class InputReader {

        private InputStream in;
        private byte[] buffer = new byte[1024];
        private int curbuf;
        private int lenbuf;

        public InputReader(InputStream in) {
            this.in = in;
            this.curbuf = this.lenbuf = 0;
        }

        public boolean hasNextByte() {
            if (this.curbuf >= this.lenbuf) {
                this.curbuf = 0;
                try {
                    this.lenbuf = this.in.read(this.buffer);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (this.lenbuf <= 0) {
                    return false;
                }
            }
            return true;
        }

        private int readByte() {
            if (this.hasNextByte()) {
                return this.buffer[this.curbuf++];
            } else {
                return -1;
            }
        }

        private boolean isSpaceChar(int c) {
            return !(c >= 33 && c <= 126);
        }

        private void skip() {
            while (this.hasNextByte() && this.isSpaceChar(this.buffer[this.curbuf])) {
                this.curbuf++;
            }
        }

        public boolean hasNext() {
            this.skip();
            return this.hasNextByte();
        }

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

        public int nextInt() {
            if (!this.hasNext()) {
                throw new NoSuchElementException();
            }
            int c = this.readByte();
            while (this.isSpaceChar(c)) {
                c = this.readByte();
            }
            boolean minus = false;
            if (c == '-') {
                minus = true;
                c = this.readByte();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = this.readByte();
            } while (!this.isSpaceChar(c));
            return minus ? -res : res;
        }

        public long nextLong() {
            if (!this.hasNext()) {
                throw new NoSuchElementException();
            }
            int c = this.readByte();
            while (this.isSpaceChar(c)) {
                c = this.readByte();
            }
            boolean minus = false;
            if (c == '-') {
                minus = true;
                c = this.readByte();
            }
            long res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res = res * 10 + c - '0';
                c = this.readByte();
            } while (!this.isSpaceChar(c));
            return minus ? -res : res;
        }

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

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

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

        public char[][] nextCharMap(int n, int m) {
            char[][] map = new char[n][m];
            for (int i = 0; i < n; i++) {
                map[i] = this.next().toCharArray();
            }
            return map;
        }
    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
    public static void main(String args[]) throws Exception{
        BufferedReader stdR = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(stdR.readLine());
        int[] p = new int[N];
        String[] s = stdR.readLine().split(" ");
        for(int i = 0 ; i < N ; i++) {
            p[i] = Integer.parseInt(s[i]);
        }
        if(isOrder(p)) {
            System.out.println("YES");
        }else {
            boolean isok = false;
            for(int i = 0 ; i < N ; i++) {
                for(int j = i + 1 ; j < N ; j++) {
                    int tmp = p[i];
                    p[i] = p[j];
                    p[j] = tmp;
                    isok = isOrder(p);
                    if(isok) {
                        System.out.println("YES");
                        break;
                    }else {
                        p[j] = p[i];
                        p[i] = tmp;
                    }
                }
                if(isok)break;
            }
            if(!isok)System.out.println("NO");
        }

    }

    public static boolean isOrder(int[] a) {
        int res = a[0];
        for(int i = 1 ; i < a.length ; i++) {
            if(res <= a[i]) {
                res = a[i];
            }else {
                return false;
            }
        }
        return true;
    }
}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);

		int numberOfInput = input.nextInt();

		int[] array = new int[numberOfInput];

			for(int i=0;i<numberOfInput;i++) {

				array[i]=input.nextInt();

			}

			        if (((array[0]+array[numberOfInput-1])%2)==0){
			            System.out.println("Yes");
			        } else {
			            System.out.println("No");
			        }

		input.close();

	}

}


import java.util.Scanner;

public class Oor1Swap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);

		int numberOfInput = input.nextInt();

		int[] array = new int[numberOfInput];

			for(int i=0;i<numberOfInput;i++) {

				array[i]=input.nextInt();

			}

			        if (((array[0]+array[numberOfInput-1])%2)==0){
			            System.out.println("Yes");
			        } else {
			            System.out.println("No");
			        }

		input.close();

	}

}


import java.util.Scanner;

public class Main{

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner input = new Scanner(System.in);

		int numberOfInput = input.nextInt();

		int[] array = new int[numberOfInput];

			for(int i=0;i<numberOfInput;i++) {

				array[i]=input.nextInt();

			}

			        if (((array[0]+array[numberOfInput-1])%2)==0){
			            System.out.println("Yes");
			        } else {
			            System.out.println("No");
			        }

			}

		input.close();

	}

}


#include <iostream>
#include <vector>
using namespace std;

int main(int argc, const char * argv[])
{
    int N;
    cin >> N;

    vector<int> P0;
    vector<int> P1;
    for (int i = 0; i < N; i++) {
        int tmp;
        cin >> tmp;
        P0.push_back(tmp);
        P1.push_back(tmp);
    }

    sort(P0.begin(), P0.end());

    int count = 0;
    for (int i = 0; i < N; i++) {
        if (P0[i] != P1[i]) {
            count++;
        }
        if (count >= 3) {
            break;
        }
    }

    if (count >= 3) {
        cout << "NO" << endl;
    }else {
     cout << "YES" << endl;
    }
}


#include<stdio.h>
#include<iostream>
#include <algorithm>

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

    int a[n];

    int num=0;
    for(int i=0;i<n-1;i++){
        if(q[i]>q[i+1]){
            if(num==0){
            a[num]=i;
            }else{
            a[num]=i+1;
            }
            num++;
        }
    }

    int tmp;
    if(num==2){
    tmp=q[a[0]];
    q[a[0]]=q[a[1]];
    q[a[1]]=tmp;
    }

    bool flag=false;
     for(int i=0;i<n-1;i++){
         //printf("%d\n",flag);
         if(q[i]>q[i+1]){
             flag=true;
         }
     }

    if(flag){
        printf("%s\n","NO");

    }else{
        printf("%s\n","YES");
    }

    return 0;
}


#include<iostream>
#include<cstdio>
#include<string>
#include<cstdlib>
#include<cstring>
using namespace std;
void aswap(int *a,int n);
int main()
{
	int n,a[50],i,i1=-1,i2=-1;
	bool s=false;
	cin>>n;
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	for(i=0;i<n-1;i++)
		if(a[i]!=i+1&&i1==-1)
		{
			i1=i;
			continue;
		}
		else if(a[i]!=i+1&&i2==-1)
		{
			i2=i;
			swap(a[i1],a[i2]);
			i=-1;
			continue;
		}
		else if(a[i]!=i+1)
		{
			break;
		}
		else if(i==n-2) s=true;
	if(s) cout<<"YES";
	else cout<<"NO";
	return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); i++)
#define lower(s) transform(s.begin(), s.end(), s.begin(), ::tolower)
using namespace std;
using ll = long long;
int INF = 1001001001;

int main()
{
  int n;
  cin >> n;
  vector<int> p(n);
  vector<int> sp(n);
  rep(i, n) {
    int v;
    cin >> v;
    p[i] = sp[i] = v;
  }
  sort(sp.begin(), sp.end());
  int cnt = 0;
  rep(i, n)
  {
    if (p[i] != sp[i])
      cnt++;
    if (cnt >= 3)
    {
      cout << "No" << endl;
      return 0;
    }
  }
  cout << "Yes" << endl;
  return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;

int main() {
  int n;
  cin >> n;
  vector<int> vec(n);
  rep(i, n) {
    cin >> vec.at(i);
  }
  auto vec2 = vec;
  sort(vec2.begin(), vec2.end());
  string ans = "No";
  if (vec == vec2) ans = "Yes";
  else {
    for(int i = 0; i < n-1; i++) {
      for(int j = i + 1; j < n; j++) {
        swap(vec.at(i), vec.at(j));
        if (vec == vec2) ans = "Yes";
        else swap(vec.at(i), vec.at(j));
      }
    }
  }
  cout << ans << endl;
}


#include <bits/stdc++.h>
using namespace std;

int main() {
  long N, x = 0, a = 0, b = 0, flag = 0;
  string ans = "Yes";
  cin >> N;

  for (int i = 1; i <= N; i++) {
    cin >> x;
    if (i != x && flag == 2) break;
    if (i != x && flag == 1) {
      if (x == a && i == b) ans = "Yes";
      flag = 2;
    }
        if (i != x && flag == 0) {
      a = i;
      b = x;
      flag = 1;
      ans = "No";
    }
  }

  cout << ans << endl;
}


#include <stdio.h>

int main(void){
    int N, i,a,b,c,d,j;
    int p[50], y=0, n=0;

    scanf("%d",&N);
    for( i=0; i<N;i++)
    scanf("%d",&p[i]);

    b=0;
    for(i=0; i<N-1;i++){
         if(p[i]>p[i+1] && b ==0 ){
            a=p[i];
            b=1;
            j=i;
         }
         else if( p[i]>p[i+1] && b==1){
             c=p[i+1];
             p[i+1]=a;
             p[j]=c;
             b = 2;
         }
    }

    for(i=0; i < N-1;i++){
        if(p[i]>p[i+1])
            n=1;
    }

    if ( N == 2)
        n = 0;

    if ( N == 3){
        for (i = 0; i<N;i++)
            if ( p[i]<p[i+1])
                n = 0;
    }

    if (n==1)
        printf("NO\n");
        else
        {
            printf("YES\n");
        }

//for (i=0;i<N;i++)
 //   printf("%d ", p[i]);

}


#include<stdio.h>
int main(void)
{
	int N;
	int count=0;
	scanf("%d", &N);
	int ary[N+1];
	for(int i=1;i<=N;i++){
		scanf("%d", &ary[i]);
		if(ary[i]==i){
			count=count+0;
			}
		else{count++;}

	}
	if(count==0 || count==2 ||count==1)printf("YES");
	else printf("NO");
	return 0;

}


#include<stdio.h>
#include<stdlib.h>

int main(void){
    int N;
    int i, j, k, l, m;
    int A;
    scanf("%d",&N);
    int p[N];
    for(i=0;i<N;i++){
        scanf("%d",&p[i]);
    }
// irekae
    for(j=0;j<N-1;j++){
        if(p[j+1]-p[j] < 1){
            A = p[j];
            p[j] = j+1;
            break;
        }
    }
    for(l=0;l<N-1;l++){
         if(p[l+1]-p[l] < 1){
            p[l+1] = A;
        }
    }
//    for(m=0;m<N;m++){
//        printf("a%d\n",p[m]);
//    }
//hantei
    for(k=0;k<N-1;k++){
        if(p[k+1]-p[k] != 1){
            printf("NO\n");
            exit(0);
        }
    }
    printf("YES\n");
    return 0;
}


#include<stdio.h>
#define SIZE 10000
int main()
{
    int i,n,a[SIZE],swp=0,tmp;
    scanf("%d", &n);
    for(i=0;i<n;i++)
    {
        scanf("%d", &a[i]);
    }
    for(i=0;i<n;i++)
    {
        if(a[i]<a[i+1])
        {
            tmp = a[i];
            a[i] = a[i+1];
            a[i+1] = tmp;
            swp += 1;
        }
    }
    if(swp<=2) printf("Yes\n");
    else printf("No\n");
    return 0;
}


#include<stdio.h>
#define SIZE 100000
int main()
{
    int i,n,a[SIZE],swp=0,tmp;
    scanf("%d", &n);
    for(i=0;i<n;i++)
    {
        scanf("%d", &a[i]);
    }
    for(i=0;i<n;i++)
    {
        if(a[i]<a[i+1])
        {
            tmp = a[i];
            a[i] = a[i+1];
            a[i+1] = tmp;
            swp += 1;
        }
    }
    if(swp<=2) printf("Yes\n");
    else printf("No\n");
    return 0;
}


#include<stdio.h>
#define SIZE 100000
int main()
{
    int i,n,a[SIZE], a1[SIZE],count=0;
    scanf("%d", &n);
    for(i=1;i<=n;i++)
    {
        a[i]=i;
    }
    for(i=1;i<=n;i++)
    {
        scanf("%d", &a1[i]);
        if(a1[i]!=a[i])
        {
            count++;
        }
    }
    if(count<=2) printf("Yes\n");
    else printf("No\n");
    return 0;
}


function Main(input) {
	inputs = input.split("\n");
	input = inputs[1].split(" ").map(Number);
	ans = true;
	culc = 0;
	temp = 0;

	for(var i = 0; i < input.length - 1; i++){
		if(input[i + 1] < input[i]){
			if(culc == 0){
				temp = input[i];
				number = i;
				culc++;
			}else{
				input[number] = input[i + 1];
				input[i + 1] = temp;
			}
		}
	}

	for(var i = 0; i < input.length - 1; i++){
		if(!(input[i] < input[i + 1])){
			ans = false;
		}
	}

	if(ans){
		console.log("YES");
	}else{
		console.log("NO");
	}

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


function main(c){var b=c.split("\n");c=parseInt(b[0]);var d=[];b[1]=b[1].split(" ");for(var a=0;a<c;++a)d.push(parseInt(b[1][a],10));for(a=b=0;a<c;++a)d[a]!=a+1&&(b+=1);console.log(2>=b?"YES":"NO")}main(require("fs").readFileSync("/dev/stdin","utf8"));


'use strict';(function(input){

  input=input.trim().split(/\s+/).map(x=>x-0);

  const N = input[0];
  var counter = 0;
  for(let i=1;i<=N;i++){
    if(i!==input[i]){
      counter++;
    }
  }
  if(counter<=2){
    console.log('YES');
  }else{
    console.log('NO');
  }
})(require('fs').readFileSync('/dev/stdin','utf8'));


const main = input => {
  const inputs = input.trim().split('\n')

  const N = parseInt(inputs[0])
  const sequence = inputs[1].split(' ').map(x => parseInt(x))

  const sortedSample = sequence.slice().sort((a, b) => a - b)

  let diff = 0
  for (let i = 0; i < N; i++) {
    console.log(sequence[i], sortedSample[i]);
    if (sequence[i] !== sortedSample[i]) {
      diff++
    }
  }

  diff === 2 || diff === 0 ? console.log('YES') : console.log('NO')

}
// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))


const main = input => {
  const inputs = input.trim().split('\n')

  const N = parseInt(inputs[0])
  const sequence = inputs[1].split(' ')

  const sortedSample = sequence.slice().sort()

  let diff = 0
  for (let i = 0; i < N; i++) {
    if (sequence[i] !== sortedSample[i]) {
      diff++
    }
  }

  diff === 2 || diff === 0 ? console.log('YES') : console.log('NO')

}
// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))


"use strict";
function main(input) {
    const line = input.split("\n");
    const N = parseInt(line[0]);
    const p = line[1].split(" ").map(Number);
    let cnt = 0;
    for (let i = 0; i < N; i++) if (p[i] !== i + 1) cnt++;
    if (cnt <= 2) console.log("Yes");
    else console.log("No");
    return;
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


package main

import "fmt"

func main() {
	var N int
	fmt.Scanf("%d", &N)
	P := make([]int, N)
	for i := 0; i < N; i++ {
		fmt.Scanf("%d", &P[i])
	}
	mismatch := 0
	for i := 0; i < N; i++ {
		if P[i] != i+1 {
			mismatch++
		}
	}
	if mismatch == 0 || mismatch == 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

const (
	defaultBufferSize = 1024
	maxBufferSize     = 1e6
	Mod               = 1e9 + 7
)

var sc = bufio.NewScanner(os.Stdin)

// sc.Buffer(make([]byte, defaultBufferSize), maxBufferSize)

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

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

func readInt64() int64 {
	sc.Scan()
	i, err := strconv.ParseInt(sc.Text(), 10, 64)
	if err != nil {
		panic(err)
	}
	return int64(i)
}

func readfloat64() float64 {
	sc.Scan()
	f, err := strconv.ParseFloat(sc.Text(), 64)
	if err != nil {
		panic(err)
	}
	return f
}

func abs(a int) int {
	if a < 0 {
		return a * -1
	}
	return a
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

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

func gcd(x, y int) int {
	if y == 0 {
		return x
	}
	return gcd(y, x%y)
}

func ModComb(n, k int) int {
	if k == 0 {
		return 1
	}
	x, y := n, k
	for i := 1; i < k; i++ {
		x = x * (n - i) % Mod
		y = y * (k - i) % Mod
	}
	inv := ModInv(y)
	return x * inv % Mod
}

func ModFact(x int) int {
	fact := 1
	for i := 1; i <= x; i++ {
		fact = fact * i % Mod
	}
	return fact
}

func ModInv(x int) int {
	return ModPow(x, Mod-2)
}

func ModPow(a, n int) int {
	res := 1
	for n > 0 {
		if n%2 != 0 {
			res = res * a % Mod
		}
		a = a * a % Mod
		n /= 2
	}
	return res
}

func pow(a, n int) int {
	if n == 0 {
		return 1
	}

	ans := 0
	if n%2 == 0 {
		ans = pow(a*a, n/2)
	} else {
		ans = a * pow(a*a, (n-1)/2)
	}
	return ans
}

func intSliceReverse(slice []int) []int {
	for i, j := 0, len(slice)-1; i < j; i, j = i+1, j-1 {
		slice[i], slice[j] = slice[j], slice[i]
	}
	return slice
}

func stringReverse(str string) string {
	runes := []rune(str)
	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 primeFactorization(x int) map[int]int {
	result := make(map[int]int, 0)
	for i := 2; i*i <= x; i++ {
		for x%i == 0 {
			result[i]++
			x /= i
		}
	}
	if x != 1 {
		result[x]++
	}
	return result
}

func isPrime(x int) bool {
	if x == 1 {
		return false
	}
	for i := 2; i*i <= x; i++ {
		if i == x {
			continue
		}
		if x%i == 0 {
			return false
		}
	}
	return true
}

func main() {
	sc.Split(bufio.ScanWords)
	n := readInt()
	p := make([]int, n)
	for i := 0; i < n; i++ {
		p[i] = readInt()
	}

	pasc := make([]int, n)
	copy(pasc, p)
	sort.Ints(pasc)

	count := 0
	for i, _ := range p {
		if p[i] != pasc[i] {
			count++
		}
	}
	if count <= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

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

var scanner = bufio.NewScanner(os.Stdin)

func scanLine() []int {
	var s []int
	scanner.Scan()
	for _, v := range strings.Split(scanner.Text(), " ") {
		i, _ := strconv.Atoi(v)
		s = append(s, i)
	}
	return s
}
func main() {
	var n int
	fmt.Scan(&n)
	p := scanLine()

	var SameWithIndex int
	for i, v := range p {
		if i+1 == v {
			SameWithIndex++
		}
	}
	if n-SameWithIndex <= 2 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


#include <bits/stdc++.h>
using namespace std;
using ll=long long;
const ll MOD=(ll)1e9+7;
const ll INF=(ll)1e18+10;
const double PI=acos(-1);

template<class T> bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T> bool chmin(T &a, const T &b) { if (a>b) { a=b; return 1; } return 0; }
int dy[]={-1,1,0,0};
int dx[]={0,0,-1,1};

bool check(const vector<int> &a){
    int maxi=a[0];
    for (int i = 1; i < a.size(); ++i) {
        if(a[i]<maxi) return false;
        maxi = a[i];
    }
    return true;
}

void solve(int cn) {
    int N; cin>>N;
    vector<int> a(N);
    for (int i = 0; i < N; ++i) {
        cin>>a[i];
    }

    if(check(a)){
        cout<<"YES"<<endl;
        return;
    }

    for (int i = 0; i < N; ++i) {
        for (int j = i+1; j < N; ++j) {
            swap(a[i],a[j]);
            if(check(a)){
                cout<<"YES"<<endl;
                return;
            }
            swap(a[i],a[j]);
        }
    }
    cout<<"NO"<<endl;

}

#define SINGLE
int main() {
#ifdef SINGLE
    solve(1);
#else
    int N;
    cin>>N;
    for(int i=0;i<N;++i){
        solve(i);
    }
#endif
    return 0;
}


package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	before := 0
	count := 0
	for i := 0; i < n; i++ {
		var v int
		fmt.Scanf("%d", &v)
		if v - before != 1 {
			count++
		}
		before++
	}
	fmt.Println(count)
	if count == 2 || count == 0 {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	before := 0
	count := 0
	for i := 0; i < n; i++ {
		var v int
		fmt.Scanf("%d", &v)
		if v - before != 1 {
			count++
			i++
		}
		before++
	}
	if count == 2 || count == 0  {
		fmt.Println("YES")
	} else {
		fmt.Println("NO")
	}
}


n = gets.chomp.to_i
p = gets.chomp.split(' ').map(&:to_i)
diff = 0
(1..n).each.with_index do |num, i|
  diff += 1 if (num != p[i])
end

if (diff == 0 || diff == 2)
  puts 'YES'
else
  puts 'NO'
end


n = gets.to_i
p = gets.chomp.split.map(&:to_i)
x = p.sort

sum = 0
p.zip(x).each do |i,y|
  if i == y
    sum += 1
  end
end

if sum >= n-2
  puts "YES"
else
  puts "NO"
end


N=gets.to_i
A=gets.split.map(&:to_i)

cnt=0
N.times do |i|
  if A[i] != i + 1
    cnt+=1
  end
end

if cnt == 2 || cnt == 0
  puts "YES"
else
  puts "NO"
end


n,*a=`dd`.split.map(&:to_i)
b=a.sort
c=0
n.times do |i|
  c+=1 if a[i]!=b[i]
  if c>1
    puts 'NO'
    exit
  end
end
puts 'YES'


n=gets.to_i
s=gets.chomp
a=s.sort
sum=0
for i in 0..n-1
  sum+=1 if s[i]!=a[i]
end
puts sum<=2? :YES: :NO


N = gets.to_i
P = gets.split.map(&:to_i)
s = P.sort

diff = 0
(0...N).each do |i|
  if P[i] != s[i]
    diff += 1
  end
end

if diff <= 2
  print "Yes\n"
else
  print "No\n"
end


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

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

fn main() {
    let n : usize = read();
    let v :Vec<usize> = read_vec();
    let mut c = 0;
    for i in 0..n {
        if v[i] != i+1 {
            c += 1;
        }
    }
    if c > 2 || c == 1 {
        println!("NO");
    }
    else {
        println!("YES");
    }
}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let n = match buf.trim().parse::<i32>(){
		Ok(n) => n,
		_ => panic!(""),
	};
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v = Vec::new();
	for i in iter {
		match i.parse::<i32>() {
			Ok(j) => v.push(j),
			_ => panic!(""),
		}
	}
	let mut cnt = 0;
	for i in 0..n {
		if v[i as usize] != i + 1 {
			cnt += 1;
		}
		if cnt > 2 {
			break;
		}
	}
	if cnt > 2 {
		println!("NO");
	}else{
		println!("YES");
	}
}


macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

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

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

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

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

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

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

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

fn main(){

    input!{
        n: usize,
        p: [usize;n],
    }

    // let mut flag: bool = true;
    // let mut p_tmp:Vec<usize> = Vec::new();

    // for &value in &p{
    //     p_tmp.push(value);
    // }

    // for i in 0..n-1{
    //     for j in i..n{
    //         p_tmp.swap(i,j);
    //         flag = true;
    //         for k in 0..n-1{
    //             if p_tmp[k+1] < p_tmp[k]{
    //                 flag = false;
    //                 break;
    //             }
    //         }
    //         if flag == true {
    //             println!("YES");
    //             return;
    //         }
    //         p_tmp.swap(j,i);
    //     }
    // }

    // if flag == false{
    //     println!("NO");
    // }

    let mut cnt = 0;
    for i in 0..n{
        if p[i]!=i+1 {
            cnt+=1;
        }
    }

    if cnt > 2 {
        println!("NO");
    } else {
        println!("YES");
    }

}


#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

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

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

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn f(s: &Vec<i32>) -> bool{

    return true;
}

use std::iter::Iterator;
use std::cmp;

fn main() {
    input! {
        n : usize,
        p : [usize;n]
    }

    let mut cnt = 0;

    for (i ,val) in p.iter().enumerate() {
        if (i + 1) != *val {
            cnt = cnt + 1;
        }
    }

    if cnt == 2 {
        println!("YES");
    } else{
        println!("NO")
    }

}


#[allow(unused_macros)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

#[allow(unused_macros)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

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

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

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

fn f(s: &Vec<i32>) -> bool{

    return true;
}

use std::iter::Iterator;
use std::cmp;

fn main() {
    input! {
        n : usize,
        p : [usize;n]
    }

    let mut cnt = 0;

    for (i ,val) in p.iter().enumerate() {
        if (i + 1) != *val {
            cnt = cnt + 1;
        }
    }

    if cnt == 2 {
        println!("Yes");
    } else{
        println!("No")
    }

}


use std::io;

fn main() {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let n = match buf.trim().parse::<i32>(){
		Ok(n) => n,
		_ => panic!(""),
	};
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v = Vec::new();
	for i in iter {
		match i.parse::<i32>() {
			Ok(j) => v.push(j),
			_ => panic!(""),
		}
	}
	let mut cnt = 0;
	for i in 1..(n+1) {
		if v[i as usize] != i {
			cnt += 1;
		}
		if cnt > 2 {
			break;
		}
	}
	if cnt > 2 {
		println!("NO");
	}else{
		println!("YES");
	}
}


let n=Int(readLine()!)!
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
var pp=readInts()
let ppw=pp.sorted()
var count=0
for i in 0...n-1{
  if pp[i] != ppw[i]{
    count+=1
  }
}
if count==2 || count==0{
  print("YES")
}else{
  print("NO")
}


readLine();let i=readLine()!.characters.split(" ").enumerate().reduce(0){$0+($1.0+1==Int(String($1.1))! ?0:1)};print(i==0||i==2 ?"YES":"NO")


let a=Int(readLine()!)!
let arr=readLine()!.characters.split{$0==" "}.map{Int(String($0))!}

var i = 0
var diff = 0

for i in 0..<a {
  if( arr[i] != i + 1 ) {
    diff += 1
  }

}

if ( diff <= 2 ) {
  print( "YES" )
} else {
  print( "NO" )
}


import Foundation

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

let reader=readInts()
let n=reader[0]
var p=readInts()
var sorted=p
sorted.sort { $0 < $1 }
var diff=0

for i in 0..<n{
  if p[i] != sorted[i]{diff+=1}
}

if diff==2||diff==0{print("Yes")}else{print("No")}


let n=Int(readLine()!)!
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
var pp=readInts()
let ppw=pp.sorted()
var count=0
for i in 0...n-1{
  if pp[i] != ppw[i]{
    count+=1
  }
}
if count==2{
  print("YES")
}else{
  print("NO")
}


let n=Int(readLine()!)!
func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}
var pp=readInts()
let ppw=pp.sorted()
var count=0
for i in 0...n-1{
  if pp[i]!=ppw[i]{
    count+=1
  }
}
if count==2{
  print("YES")
}else{
  print("NO")
}


const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')
const data = stdin
  .trim()
  .split('\n')[1]
  .split(' ')
  .map(n => Number.parseInt(n))

const x = data.map((n, i) => (n === i + 1 ? 0 : 1)).reduce((prev, cur) => prev + cur, 0)

console.log(x === 0 || x === 2 ? 'YES' : 'NO')


function main(input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const ps = input[1].split(" ").map(a => Number(a));
  const indices = [];
  for(let i = 0; i < n; i++) {
    const p = ps[i];
    if (i+1 !== p) indices.push(i);
  }
  let result = "NO";
  if (indices.length === 0 || indices.length === 2) result = "YES";
  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));


export class Main {
  static main(input): string {
    const tmp: string[] = input.split("\n");
    const n: number = tmp[0].split(" ").map(int => parseInt(int))[0];
    const p: number[] = tmp[1].split(" ").slice(0, n).map(int => parseInt(int));
    const pCopy: number[] = [].concat(p);
    pCopy.sort((a, b) => a - b);
    let count: number = 0;
    for (let i = 0; i < n; i++) {
      if (p[i] != pCopy[i]) {
        count++;
      }
    }
    return `${count == 0 || count == 2 ? "YES" : "NO"}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


import * as fs from 'fs';

namespace AtCoder.abc135 {

    export class Program {
        args: string[];

        constructor(args: string[]) {
            this.args = args;
        }

        /**
         * in
         * 5
         * 5 2 3 4 1
         * out
         * Yes
         */
        main(): void {
            let p: number [] = this.args[1].split(' ').map(x => parseInt(x, 10));
            const sorted: number[] = this.args[1].split(' ').map(x => parseInt(x, 10)).sort();

            let cnt: number = 0;
            for (let i = 0; i < p.length; i++) {
                if (p[i] !== sorted[i]) {
                    cnt++;
                }
                if (cnt > 2) {
                    console.log('NO');
                    return;
                }
            }
            console.log('YES');
        }
    }

}

const args = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const prg = new AtCoder.abc135.Program(args);
prg.main();


import * as fs from 'fs';

namespace AtCoder.abc135 {

    export class Program {
        args: string[];

        constructor(args: string[]) {
            this.args = args;
        }

        /**
         * in
         * 5
         * 5 2 3 4 1
         * out
         * Yes
         */
        main(): void {
            let p: number [] = this.args[1].split(' ').map(x => parseInt(x, 10));
            const sorted: number[] = this.args[1].split(' ').map(x => parseInt(x, 10)).sort();

            let cnt: number = 0;
            for (let i = 0; i < p.length; i++) {
                if (p[i] !== sorted[i]) {
                    cnt++;
                }
                if (cnt > 2) {
                    console.log('No');
                    return;
                }
            }
            console.log('Yes');
        }
    }

}

const args = fs.readFileSync('/dev/stdin', 'utf8').trim().split('\n');
const prg = new AtCoder.abc135.Program(args);
prg.main();


const t={input:require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/),n:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.n())}return a}else{const a=t.input[0];t.input.shift();return Number(a)}},s:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.s())}return a}else{const a=t.input[0];t.input.shift();return String(a)}},c:(arg:number=0):any=>{if(arg){const a=[];for(let i=0;i<arg;i++){a.push(t.c())}return a}else{let a=t.input[0].split('');const b=a[0];a.shift();if(a.length>0){t.input[0]=a.join('')}else{t.input.shift()}return String(b)}},o:(...arg)=>{console.log(...arg)},abs:(a)=>{return Math.abs(a)},min:(...a)=>{return Math.min(...a)},max:(...a)=>{return Math.max(...a)},floor:(a)=>{return Math.floor(a)},asc:(ar:number[])=>{return ar.sort((a,b)=>{return a-b})},desc:(ar:number[])=>{return ar.sort((a,b)=>{return b-a})},sw:(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length;i+=2){if(eval(a+op+arr[i]))return arr[i+1];}return arr[arr.length-1]}};
const main=()=>{
  let n=t.n()
  let s=t.n(n)
  let c=0;
  for(let i=0;i<n;i++){
    if(s[i] != i+1) c++
  }
  t.o(c==2?'YES':'NO')
}
main()


N,x = map(int,input().split())
li = list(map(int,input().split()))

newLi = sorted(li)
ans = 0

for i in range(len(newLi)):
  if x - newLi[i] < 0:
    break

  if i == (len(newLi) - 1) and x != newLi[i]:
    break

  x -= newLi[i]
  ans += 1

print(ans)


N, x = map(int, input().split())
a = list(map(int, input().split()))

# 小さい数から配っていくと子供の人数を最大化できる
a = sorted(a)

leftCandy = x
childrenCnt = 0
for i in range(len(a)):
  leftCandy -= a[i]
  if leftCandy >= 0:
    childrenCnt += 1

if leftCandy > 0:
  childrenCnt -= 1

print(childrenCnt)


N, x = map(int,input().split())
a = list(map(int,input().split()))
a.sort()
count = 0
for i in range(N):
    x = x - a[i]
    if x < 0:
        break
    count += 1
if x > 0:
    count -= 1
print(count)


N,x=input().split()
X=int(x)
n=int(N)
y=0
A = [int(i) for i in input().split()]
A.sort()
for z in range(n):
  y+=A[z]
  if y>=X:
    break
    print(z+1)
else:
  print(n-1)


N,x=input().split()
X=int(x)
n=int(N)
y=0
A = [int(i) for i in input().split()]
A.sort()
for z in range(n):
  y+=A[z]
  if y>=X:
    print(z+1)
    break
else:
  print(N)


N,x=input().split()
X=int(x)
n=int(N)
y=0
A = [int(i) for i in input().split()]
A.sort()
for z in range(n):
  y+=A[z]
  if y>=X:
    print(z+1)
    break


import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;

public class Main {

	public static void main(String[] args) throws IOException {
		Main m = new Main();
		//*
		m.input();
		m.solve();
		m.output();
		/*/
		m.debug();
		//*/
	}

	public void debug() {
	}

	InputUtil in = new InputUtil();
	PrintWriter out = new PrintWriter(System.out);
	int N = 0;
	int x = 0;
	int[] A = null;
	long ans = 0;

	public void input() throws IOException {
		N = in.nextInt();
		x = in.nextInt();
		A = in.nextInt(new int[N]);
	}

	public void solve() throws IOException {
		Arrays.sort(A);
		for (int i=0; i<N; i++) {
			int a = A[i];
			if (i == N-1) {
				if (a == x) {
					ans ++;
				}
			} else if (a <= x) {
				x -= a;
				ans ++;
			} else {
				x = 0;
			}
		}
	}

	public void output() {
		out.println(ans);
		out.flush();
	}

}

class InputUtil {
	//Static Fields
	private static final int BUFSIZ = 100000;
	boolean lineMode = false;

	//Fields
	protected InputStream in;
	private byte[] buf = null;
	private int ptr = 0;
	private int max = -1;
	private DataInputStream dis = null;
	//Constructors
	public InputUtil() {this(System.in,BUFSIZ);}
	public InputUtil(InputStream in, int bufsiz) {
		initBuf(bufsiz);
		initIn(in);
	}

	//Methods
	//Initializer
	protected void initIn(InputStream in) {dis = new DataInputStream(this.in = in);}
	protected void initBuf(int bufsiz) {buf = new byte[bufsiz];}

	//buffer operation
	private void next() throws IOException {ptr++; readBuf();}
	private void readBuf() throws IOException {
		if(ptr >= max && dis.available()>0) {
			if(max>0) Arrays.fill(buf,0,max,(byte)0);
			max = dis.read(buf);
			ptr = 0;
		}
	}

	//String Input Reader/Parser
	private boolean isCrLf(byte b) {return b == 0x0a || b == 0x0d; }

	private void skipOneCrLf() throws IOException {
		byte b = buf[ptr];
		if (isCrLf(b)) {
			ptr++;
			if (b == 0x0d) {
				readBuf();
				if (ptr < max && buf[ptr] == 0x0a) {
					ptr++;
				}
			}
		}
	}

	public String nextLine() throws IOException {
		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;
		for(readBuf(); ptr < max ;readBuf()) {
			byte b = buf[ptr];
			if(isCrLf(b)) {
				skipOneCrLf();
				if (!isFirst || lineMode) {
					break;
				}
			}else{
				int strPtr = ptr++;
				int endPtr = -1;
				for(int i = ptr; i<max; i++) {
					if(isCrLf(buf[i])) {
						endPtr = i;
						break;
					}
				}
				if(endPtr == -1) endPtr = max;
				sb.append(new String(buf,strPtr,endPtr-strPtr,"UTF-8"));
				ptr = endPtr;
			}
			isFirst = false;
		}
		lineMode = true;
		return sb.toString();
	}

	public byte nextByte() throws IOException {
		lineMode=false;
		readBuf();
		if(ptr < max) {
			return buf[ptr++];
		}else{
			return -1;
		}
	}

	//Number Input Reader/Parser
	private boolean isNum(byte b) {return '0' <= b && b <= '9'; }
	private boolean isMinus(byte b) {return b=='-'; }

	public int nextInt() throws IOException {
		lineMode=false;
		readBuf();
		return (int)_nextLong();
	}

	public int[] nextInt(int[] result) throws IOException {
		lineMode=false;
		readBuf();
		for(int i=0; i<result.length; i++) {
			result[i] = (int)_nextLong();
		}
		return result;
	}

	private long _nextLong() throws IOException {
		int sign = 1;
		long res = 0;
		byte c;
		while (!isNum(c=buf[ptr]) && !isMinus(c))
			next();
		if (isMinus(buf[ptr])) {
			sign = -1;
			next();
		}
		while (isNum(c=buf[ptr])) {
			res *= 10;
			res += c - '0' ;
			next();
		}
		next();
		return sign * res;
	}

	public long nextLong() throws IOException {
		lineMode=false;
		readBuf();
		return _nextLong();
	}

	public long[] nextLong(long[] result) throws IOException {
		lineMode=false;
		readBuf();
		for(int i=0; i<result.length; i++) {
			result[i] = _nextLong();
		}
		return result;
	}

	//Close
	public void close() throws IOException {
		if(!this.in.equals(System.in))
			this.in.close();
	}

}

class OutputUtil {
	public static final String EOF = System.lineSeparator();

	public static void outputDivSpace(PrintWriter out, int[] a) {
		OutputUtil.output(out,a,0,a.length," ");
	}

	public static void outputDivEOF(PrintWriter out, int[] a) {
		OutputUtil.output(out,a,0,a.length,EOF);
	}

	public static void output(PrintWriter out, int[] a, int off, int len, String delim) {
		out.print(a[off]);
		for(int i=off+1; i<len; i++){
			out.print(delim);
			out.print(a[i]);
		}
		out.println("");
		out.flush();
	}
}


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) {
		}
    }

}


import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;

public class Main {
class Node {
    int id;
    long x;
    public Node(int id,long x){
        this.id=id;
        this.x=x;
    }
    public boolean equals(Object o){
        Node c=(Node)o;
        return id==c.id && x==c.x;
    }
    public int hashCode(){
        return (int)(id+x);
    }
}
    void solve(){
        int n=ni();
       long  x=nl();
        a=new long[n+1];
        for(int i=1;i<=n;i++) a[i]=nl();
        Arrays.sort(a,1,n+1);
        int ans=0;
        int id=0;
        for(int i=1;i<=n;i++){
            if(x-a[i]>=0){
                x-=a[i];
                ans++;
                id=i;
            }else break;
        }
        if(x!=0 && ans>0) {
            if(id==n) ans--;

        }
        pw.println(ans);
}

    long a[];

    long M=(long)1e9+7;
    InputStream is;
    PrintWriter pw;
    String INPUT = "";
    void run() throws Exception {
        is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
        pw = new PrintWriter(System.out);
        long s = System.currentTimeMillis();
        solve();
        pw.flush();
        if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");

    }

    public static void main(String[] args) throws Exception { new Main().run(); }

    private byte[] inbuf = new byte[1024];
    public int lenbuf = 0, ptrbuf = 0;

    private int readByte() {
        if(lenbuf == -1)throw new InputMismatchException();
        if(ptrbuf >= lenbuf){
            ptrbuf = 0;
            try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
            if(lenbuf <= 0)return -1;
        }
        return inbuf[ptrbuf++];
    }

    private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
    private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

    private double nd() { return Double.parseDouble(ns()); }
    private char nc() { return (char)skip(); }

    private String ns() {
        int b = skip();
        StringBuilder sb = new StringBuilder();
        while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
            sb.appendCodePoint(b);
            b = readByte();
        }
        return sb.toString();
    }

    private char[] ns(int n) {
        char[] buf = new char[n];
        int b = skip(), p = 0;
        while(p < n && !(isSpaceChar(b))){
            buf[p++] = (char)b;
            b = readByte();
        }
        return n == p ? buf : Arrays.copyOf(buf, p);
    }

    private char[][] nm(int n, int m) {
        char[][] map = new char[n][];
        for(int i = 0;i < n;i++)map[i] = ns(m);
        return map;
    }

    private int[] na(int n) {
        int[] a = new int[n];
        for(int i = 0;i < n;i++)a[i] = ni();
        return a;
    }

    private int ni() {
        int num = 0, b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }

    private long nl() {
        long num = 0;
        int b;
        boolean minus = false;
        while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
        if(b == '-'){
            minus = true;
            b = readByte();
        }

        while(true){
            if(b >= '0' && b <= '9'){
                num = num * 10 + (b - '0');
            }else{
                return minus ? -num : num;
            }
            b = readByte();
        }
    }
    private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
    private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); }
}


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);
    }

}


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);
    }

}


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);
    }

}


#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;
}


#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;
}


#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;
}


// #define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep2(i, l, r) for (int i = (l); i < (r); i++)
#include <bits/stdc++.h>

// #include <atcoder/all>
using namespace std;
// using namespace atcoder;
using ll = long long;
using P = pair<int, int>;
using V = vector<int>;
using VV = vector<V>;

template <class T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
//~ int A = (1<<2) | (1<<3) | (1<<5) | (1<<7);
//~ for (int bit=A; ; bit=(bit-1)&A){
//~ if (!bit) break;
//~ }
int next_combination(int sub) {
    int x = sub & -sub, y = sub + x;
    return (((sub & ~y) / x) >> 1) | y;
}
//~ int n=5;
//~ int k=3; // nCkの組み合わせ、ただしk=0には対応してない
//~ int bit=(1<<k)-1; // 1000 -> 0111
//~ for(; bit < (1<<n); bit=nex_combination(bit){
//~ }
bool isPrime(int a) {
    if (a == 2) return true;
    if (a <= 1 || a % 2 == 0) return false;

    for (int i = 3; i * i <= a; i += 2) {
        if (a % i == 0) return false;
    }
    return true;
}
//~ vector<int> a = {1, 14, 32, 51, 51, 51, 243, 419, 750, 910};
vector<int> aaa;
// index が条件を満たすかどうか
bool isOK(int index, int key) {
    if (aaa[index] >= key)
        return true;
    else
        return false;
}
// 汎用的な二分探索のテンプレ
int binary_search(int key) {
    int ng = -1;  //「index = 0」が条件を満たすこともあるので、初期値は -1
    int ok =
        (int)aaa
            .size();  // 「index =
                      // a.size()-1」が条件を満たさないこともあるので、初期値は
                      // a.size()

    /* ok と ng のどちらが大きいかわからないことを考慮 */
    while (abs(ok - ng) > 1) {
        int mid = (ok + ng) / 2;

        if (isOK(mid, key))
            ok = mid;
        else
            ng = mid;
    }
    return ok;
}

long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

//~ int v[100100];
//~ int INF = 1 << 30;
//~ vector<vector<int>> dp(310, vector<int>(310));
//~ ll dp[110][100100];
//~ vector<int> dp(100100, 0));

//~ int seen[110];
//~ int ans[110][2];
//~ ll MOD = 1e9 + 7;

void memo() {
    // int n = 100;
    // vector<int> a(n);
    // rep(i, n) {
    //     cin >> a[i];
    //     a[i]--;
    // }

    // vector<int> ans(n);
    // iota(ans.begin(), ans.end(), 0);
    // sort(ans.begin(), ans.end(), [&](int i, int j) { return a[i] < a[j]; });

    // double t1 = 0.1;
    // cout << fixed << setprecision(6) << t1 << endl;

    // int x;
    // cin >> x;

    // int n1 = 200001;
    // vector<int> ans1;
    // vector<int> primes(n, 1);
    // int i;
    // for (i = 2; i * i <= n; i++) {
    //     if (primes[i]) ans1.push_back(i);
    //     for (int j = i; j <= n; j += i) { primes[j] = 0; }
    // }
    // for (; i < n; i++) {
    //     if (primes[i]) { ans1.push_back(i); }
    // }

    // cout << *lower_bound(ans1.begin(), ans1.end(), x) << endl;
}

int main() {
    int n, x;
    cin >> n >> x;

    vector<int> a(n);
    rep(i, n) cin >> a[i];

    vector<int> acted(n, 0);
    rep(i, n) {
        if (a[i] <= x) {
            x -= a[i];
            acted[i] = a[i];
        } else {
            break;
        }
    }
    acted.back() += x;

    int ans = 0;
    rep(i, n) {
        if (a[i] == acted[i]) ans++;
    }

    cout << ans << endl;

    return 0;
}


// #define _GLIBCXX_DEBUG
#define rep(i, n) for (int i = 0; i < (n); i++)
#define rep2(i, l, r) for (int i = (l); i < (r); i++)
#include <bits/stdc++.h>

// #include <atcoder/all>
using namespace std;
// using namespace atcoder;
using ll = long long;
using P = pair<int, int>;
using V = vector<int>;
using VV = vector<V>;

template <class T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template <class T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}
//~ int A = (1<<2) | (1<<3) | (1<<5) | (1<<7);
//~ for (int bit=A; ; bit=(bit-1)&A){
//~ if (!bit) break;
//~ }
int next_combination(int sub) {
    int x = sub & -sub, y = sub + x;
    return (((sub & ~y) / x) >> 1) | y;
}
//~ int n=5;
//~ int k=3; // nCkの組み合わせ、ただしk=0には対応してない
//~ int bit=(1<<k)-1; // 1000 -> 0111
//~ for(; bit < (1<<n); bit=nex_combination(bit){
//~ }
bool isPrime(int a) {
    if (a == 2) return true;
    if (a <= 1 || a % 2 == 0) return false;

    for (int i = 3; i * i <= a; i += 2) {
        if (a % i == 0) return false;
    }
    return true;
}
//~ vector<int> a = {1, 14, 32, 51, 51, 51, 243, 419, 750, 910};
vector<int> aaa;
// index が条件を満たすかどうか
bool isOK(int index, int key) {
    if (aaa[index] >= key)
        return true;
    else
        return false;
}
// 汎用的な二分探索のテンプレ
int binary_search(int key) {
    int ng = -1;  //「index = 0」が条件を満たすこともあるので、初期値は -1
    int ok =
        (int)aaa
            .size();  // 「index =
                      // a.size()-1」が条件を満たさないこともあるので、初期値は
                      // a.size()

    /* ok と ng のどちらが大きいかわからないことを考慮 */
    while (abs(ok - ng) > 1) {
        int mid = (ok + ng) / 2;

        if (isOK(mid, key))
            ok = mid;
        else
            ng = mid;
    }
    return ok;
}

long long modpow(long long a, long long n, long long mod) {
    long long res = 1;
    while (n > 0) {
        if (n & 1) res = res * a % mod;
        a = a * a % mod;
        n >>= 1;
    }
    return res;
}

//~ int v[100100];
//~ int INF = 1 << 30;
//~ vector<vector<int>> dp(310, vector<int>(310));
//~ ll dp[110][100100];
//~ vector<int> dp(100100, 0));

//~ int seen[110];
//~ int ans[110][2];
//~ ll MOD = 1e9 + 7;

void memo() {
    // int n = 100;
    // vector<int> a(n);
    // rep(i, n) {
    //     cin >> a[i];
    //     a[i]--;
    // }

    // vector<int> ans(n);
    // iota(ans.begin(), ans.end(), 0);
    // sort(ans.begin(), ans.end(), [&](int i, int j) { return a[i] < a[j]; });

    // double t1 = 0.1;
    // cout << fixed << setprecision(6) << t1 << endl;

    // int x;
    // cin >> x;

    // int n1 = 200001;
    // vector<int> ans1;
    // vector<int> primes(n, 1);
    // int i;
    // for (i = 2; i * i <= n; i++) {
    //     if (primes[i]) ans1.push_back(i);
    //     for (int j = i; j <= n; j += i) { primes[j] = 0; }
    // }
    // for (; i < n; i++) {
    //     if (primes[i]) { ans1.push_back(i); }
    // }

    // cout << *lower_bound(ans1.begin(), ans1.end(), x) << endl;
}

int main() {
    int n, x;
    cin >> n >> x;

    vector<int> a(n);
    rep(i, n) cin >> a[i];

    vector<int> acted(n, 0);
    rep(i, n) {
        if (a[i] <= x) {
            x -= a[i];
            acted[i] = a[i];
        } else {
            acted.back() = x;
        }
    }

    int ans = 0;
    rep(i, n) {
        if (a[i] == acted[i]) ans++;
    }

    cout << ans << endl;

    return 0;
}


#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;
}


#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;
}


#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);
  }
}


#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;
}


    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;
}


#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;
}


#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;
}


// 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"));


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"));


"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"));


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'));


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'));


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'));


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))
}


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)
	}
}


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)
}


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)
}


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()
}


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()
}


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


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


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


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


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


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


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);
}


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});
}


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);
}


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);
}


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);
}


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);
}


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)


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)}


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)
}


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)
}


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)
}