(Java)프로그래머스 - 구명보트

윤준혁·2024년 4월 1일

나의 풀이

import java.util.*;

class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
        int i = 0;
        
        Arrays.sort(people); // 1
        
        for (int j = people.length - 1; j >= i ; j--) {
            if (people[i] + people[j] <= limit) i++; // 2
            answer++;
        }
        
        return answer;
    }
}

과정

  1. 제일 가벼운 사람과 제일 무거운 사람을 같이 태우기 위해 오름차순 정렬
  2. 둘을 더했을 때 limit보다 작으면 i는 증가하고 answer도 증가

다른 사람 풀이

import java.util.Arrays;

class Solution {
    public int solution(int[] people, int limit) {
        Arrays.sort(people);
        int i = 0, j = people.length - 1;
        for (; i < j; --j) {
            if (people[i] + people[j] <= limit)
                ++i;
        }
        return people.length - i;
    }
}

0개의 댓글