Question

Tony wants to buy some ice cream to cool off the summer heat.

N ice cream cakes are newly found in the store, and the array costs with length N represents the price of the ice cream, where costs[I] represents the cash price of the i-th ice cream. Tony: I have coins and I want to buy as many ice creams as possible.

I give you the price array costs and cash amount coins. Please calculate and return the maximum amount of ice cream that Tony can buy with cash coins.

Note: Tony can buy the ice cream in any order.

Train of thought

Sort first, buy what you can afford, can’t afford to pull.

solution

var maxIceCream = function(costs, coins) { var arr = costs.sort(function(a, b){return a - b}); var num = 0; var index = 0; for(let i in arr){ if(num+arr[i]<=coins){ num+=arr[i]; index++; } } return index; }; ,2,3,1,4 maxIceCream ([1], 7); The output of 4Copy the code