[프로그래머스] Level1- 예산

JIEUN YANG·2023년 1월 17일
0

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.


First, make for loop and inject statement to check each value is larger than budget.

Second, calculate remaining budget by subracting a current value in for loop and push the current value into array.

Lastly, get the length of array so that you can check the numbers of departments.


My Code.


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;
}

The point of this problem is to Sort



A simplest Code.

function solution(d, budget) {
    d.sort((a, b) => a - b);
    while (d.reduce((a, b) => (a + b), 0) > budget) {
      d.pop();
    }

    return d.length;
}
profile
violet's development note

0개의 댓글