프로그래머스

[프로그래머스] 구명보트 (javascript)

해랑쓰 2021. 3. 3. 16:53
728x90
반응형

최대 2명의 조건이 있다. 몸무게가 많이 나가는 사람을 기준으로 해야된다.

만약 여러명을 태울 수 있다면 while문안의 if문을 while로 수정하면 된다.

function solution(people, limit) {
    var answer = 0;
    people.sort((a,b)=>a-b);
    let left=0,right=people.length-1;
    let sum=0;
    while(left<=right){
        sum+=people[right];
        if(sum+people[left]<=limit){
            sum+=people[left];
            left+=1;
        }
        answer+=1;
        sum=0;
        right-=1;
    }

    return answer;
}

 

728x90
반응형