Posts Maximize Toys (geeksforgeeks - SDE Sheet)
Post
Cancel

Maximize Toys (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an array arr[] of length N consisting cost of N toys and an integer K depicting the amount with you. Your task is to find maximum number of toys you can buy with K amount.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution{
    static int toyCount(int n, int k, int arr[])
    {

        Arrays.sort(arr);

        int s = 0;
        int count = 0;

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

            if(s + arr[i] <= k){
                count++;
                s += arr[i];
            }else
                break;

        }

        return count;

    }
}
This post is licensed under CC BY 4.0 by the author.