-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmark-and-toys.js
93 lines (77 loc) · 1.94 KB
/
mark-and-toys.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
*
* -----------------
* | MARK AND TOYS |
* -----------------
*
*
* Mark and Jane are very happy after having their first child.
* Their son loves toys, so Mark wants to buy some.
* There are a number of different toys lying in front of him,
* tagged with their prices. Mark has only a certain amount
* to spend, and he wants to maximize the number of toys
* he buys with this money.
*
* Given a list of prices and an amount to spend,
* what is the maximum number of toys Mark can buy?
*
*
*
* e.g.
*
* prices = [1, 2, 3, 4] // prices of toys
* k = 7 // amount of dollars he can spend
*
* maximumToys(prices, k) // he can buy [1,2,3] for 6
*
*
* Complete the function maximumToys in the editor below.
* It should return an integer representing the maximum
* number of toys Mark can purchase.
*
* MAXIMUMTOYS HAS THE FOLLOWING PARAMETER(S):
*
* prices: an array of integers representing toy prices
* k: an integer, Mark's budget
*
*
*
* */
/*
*
* ***** SOLUTION
*
* */
function maximumToys(prices, k) {
// initialize toy counter
let counter = 0;
// sort prices
prices.sort( (a, b) => a - b );
// initialize totalCost and index to use in while loop
let totalCost = 0;
let index = 0;
console.log("sorted prices -- ", prices);
// use a while loop to find how many toys we can buy
// until total is <= k
while(prices[index] + totalCost <= k){
totalCost += prices[index];
counter ++;
index ++;
};
// return total number of toys
return counter;
};
/*
*
* ***** TESTS
*
* */
// const prices1 = [4,3,2,1]
// const k1 = 7
// console.log("## TEST 1 ----- > ", maximumToys(prices1, k1)); // 3
// const prices2 = [4,60,5,2,1]
// const k2 = 12
// console.log("## TEST 2 ----- > ", maximumToys(prices2, k2)); // 4
const prices3 = [1, 12, 5, 111, 200, 1000, 10]
const k3 = 50
console.log("## TEST 3 ----- > ", maximumToys(prices3, k3)); // 4