forked from RyanFehr/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.js
40 lines (36 loc) · 1.14 KB
/
Solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Problem: https://www.hackerrank.com/challenges/mark-and-toys
//JavaScript
/*
Initial Thoughts:
We can sort the toy prices ascending then
substract their prices from our total money
until we can no longer buy any more toys,
and since they are sorted in ascending order
we know that if we can't buy the current toy
then we can't buy any others either
Time Complexity: O(n log(n)) //It takes n log n time to sort the array
Space Complexity: O(n) //We allocate an array to store the input
*/
function processData(input) {
let setup = input.split("\n"),
params = setup[0].split(' ').map(Number),
toys = setup[1].split(' ').map(Number).sort((a,b) => a - b),
toyNum = params[0],
money = params[1],
total = 0;
while (money > 0 && total < toyNum) {
money -= toys[total];
total++;
}
console.log((total === toyNum) ? toyNum : total - 1);
}
/////////////// ignore below code \\\\\\\\\\\\\\\
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});