This problem is to get maximum how many departments you can give money based on their requesting money. Each money should be exactly the same as department’s requesting. Not to more not to less.
Thinking about how to resolve this, I dive into making steps with two arguments.
function solution(d, budget) {
let answer = [];
let remain = budget;
for(let i = 0; i< d.length; i++){
if(d[i] <= remain){
remain = remain-d[i]
answer.push(d[i])
}
}
return answer.length;
}
But, when mine was wrong in some cases. Afther being refered to other's solution, It's understandable why given "d" array should be sorted by ascending order.
So, the final solution is below
function solution(d, budget) {
let answer = [];
d.sort((a,b)=> a-b)
let remain = budget;
for(let i = 0; i< d.length; i++){
if(d[i] <= remain){
remain = remain-d[i]
answer.push(d[i])
}
}
return answer.length;
}
function solution(d, budget) {
d.sort((a, b) => a - b);
while (d.reduce((a, b) => (a + b), 0) > budget) {
d.pop();
}
return d.length;
}