본문 바로가기
알고리즘/프로그래머스

[프로그래머스][자바스크립트][Level2] 구명보트

by Benjamin_Choi 2022. 1. 8.

풀이

/**
 * 구명보트
 * 탐욕법
 * https://programmers.co.kr/learn/courses/30/lessons/42885?language=javascript
 */

function solution(people, limit) {
    let answer = 0, idx1 = 0, idx2 = people.length - 1;
    people.sort((a, b) => a - b);

    while (idx1 <= idx2) {
        if (idx1 !== idx2 && people[idx1] + people[idx2] > limit) {
            answer++;
            idx2--;
        } else {
            answer++;
            idx1++;
            idx2--;
        }
    }
    
    return answer;
}

가장 가벼운 사람을 고정해놓고 가장 무거운 사람부터 내려오면서 가벼운 사람 + 무거운 사람 or 무거운 사람 only 로 나눠서 보트를 태우는 방식이다.

 

 

 

댓글