Interview Preparation Kit/Sorting/mark_and_toys.cpp
// Complete the maximumToys function below.
Complete the maximumToys function below.
Complete the maximumToys function below .
int maximumToys(vector<int> prices, int k) {
    int bought_toys = 0;
    int money_left = k;
    sort(prices.begin(), prices.end());
    for (int x = 0; x < prices.size(); ++x) {
        if (prices[x] <= money_left) {
            money_left -= prices[x];
            ++bought_toys;
        }
        else {
            return bought_toys;
        }
    }
    return bought_toys;
}
int maximumToys ( vector < int > prices , int k ) { int bought_toys = 0 ; int money_left = k ; sort ( prices . begin ( ) , prices . end ( ) ) ; for ( int x = 0 ; x < prices . size ( ) ; ++ x ) { if ( prices [ x ] <= money_left ) { money_left -= prices [ x ] ; ++ bought_toys ; } else { return bought_toys ; } } return bought_toys ; }
Complete the maximumToys function below.
Complete the maximumToys function below .
// k denotes the amount Mark can spend (therefore he can underspend) // sort the entirety of the vector first then iterate over the sorted list // decrease money left and if next item price in vector > money then end // there are (likely) more instances of prices[x] < money_left