// Arup Guha
// 10/23/2021
// Solution to 2021 COP 3502 Fall 2021 Program #4, rewritten using Merge Sort.
// Note: I took my Merge Sort from my solution to Recitation Program #3.
/*** Edited for Spring 2022 Version: Took Out Case Loop ***/

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

// All the functions we need to sort.
void mergeSort(int* vals, int low, int high);
void merge(int* vals, int s1, int s2, int e2);

int main(void) {

    int n;
    long long maxPages;

    // Get # of books and most # of pages.
    scanf("%d%lld", &n, &maxPages);

    // Read in the # of pages in each book.
    int* books = malloc(sizeof(int)*n);
    for (int i=0; i<n; i++)
        scanf("%d", &books[i]);

    // Sort in order.
    mergeSort(books, 0, n-1);

    // Set both of these to 0.
    int res = 0;
    long long total = 0;

    // Sweep through books, smallest to largest, trying to read them.
    while (res < n) {

        // We can't read this one, get out.
        if (total + books[res] > maxPages) break;

        // Update pages read and books read.
        total += books[res];
        res++;
    }

    // Ta da!
    printf("%d\n", res);

    return 0;
}

// Merge Sorts vals[low..high].
void mergeSort(int* vals, int low, int high) {

    // Done!
    if (low >= high) return;

    // Sort left and right halves.
    int mid = (low+high)/2;
    mergeSort(vals, low, mid);
    mergeSort(vals, mid+1, high);

    // Merge together into one sorted list.
    merge(vals, low, mid+1, high);
}

// Pre-condition: vals[s1..s2-1] is sorted, vals[s2..e2] is sorted.
// Post-condition: Sorts all the values from cals[s1..e2].
void merge(int* vals, int s1, int s2, int e2) {

    // Temp array to store values.
    int* tmp = malloc(sizeof(int)*(e2-s1+1));

    // Indexes into our 3 arrays. i into left, j into right, k into tmp.
    int i = s1, j = s2, k = 0;

    // Loop till we're done filling the tmp array.
    while (k < e2-s1+1) {

        // First list is done, go to second.
        if (i==s2) tmp[k++] = vals[j++];

        // Second list is done.
        else if (j>e2) tmp[k++] = vals[i++];

        // First list is smaller.
        else if (vals[i] < vals[j]) tmp[k++] = vals[i++];

        // Must get from second list; it's smaller.
        else tmp[k++] = vals[j++];
    }

    // Copy back values.
    for (int z=0; z<e2-s1+1; z++)
        vals[z+s1] = tmp[z];
}
