본문 바로가기
CodingTest

프로그래머스 코딩테스트 연습 탐욕법 구명보트 JAVA

by KkingKkang 2025. 3. 4.

문제 설명

무인도에 갇힌 사람들을 구명보트를 이용하여 구출하려고 합니다. 구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고, 무게 제한도 있습니다.

예를 들어, 사람들의 몸무게가 [70kg, 50kg, 80kg, 50kg]이고 구명보트의 무게 제한이 100kg이라면 2번째 사람과 4번째 사람은 같이 탈 수 있지만 1번째 사람과 3번째 사람의 무게의 합은 150kg이므로 구명보트의 무게 제한을 초과하여 같이 탈 수 없습니다.

구명보트를 최대한 적게 사용하여 모든 사람을 구출하려고 합니다.

사람들의 몸무게를 담은 배열 people과 구명보트의 무게 제한 limit가 매개변수로 주어질 때, 모든 사람을 구출하기 위해 필요한 구명보트 개수의 최솟값을 return 하도록 solution 함수를 작성해주세요.

제한사항
  • 무인도에 갇힌 사람은 1명 이상 50,000명 이하입니다.
  • 각 사람의 몸무게는 40kg 이상 240kg 이하입니다.
  • 구명보트의 무게 제한은 40kg 이상 240kg 이하입니다.
  • 구명보트의 무게 제한은 항상 사람들의 몸무게 중 최댓값보다 크게 주어지므로 사람들을 구출할 수 없는 경우는 없습니다.
입출력 예peoplelimitreturn
[70, 50, 80, 50] 100 3
[70, 80, 50] 100 3

정확성 테스트는 통과했지만 효율성 테스트는 실패한 코드

import java.util.*;

class Solution{

	public int solution(int[] people, int limit){
    
    	int answer = 0;
        
        //people을 역순으로 정렬하기 
        people = Arrays.stream(people).boxed().sorted(Collections.reverseOrder()).mapToInt(Integer::intValue).toArray();
        
        for(int i=0; i<people.length; i++) {
        
        	if(people[i] == -1) continue;
            int remain = limit - people[i];
            if(remain > 0){
            	for(int j = i + 1 ; j < people.length; j++) {
                	if(people[j] <= remain && people[j] != -1) {
                    	people[j] = -1;
                        break;
                    }
                }
            }
        	answer++;
        }
    	return answer;
    }

}
import java.util.*;

class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
        
        ArrayList<Integer> list = new ArrayList<>();

        for (int x :
                people) {
            list.add(Integer.valueOf(x));
        }
        int max ,min = 0;

        while(!list.isEmpty()){
            max = Collections.max(list);
            list.remove(Integer.valueOf(max));
            if(max < limit && !list.isEmpty()){
                min = Collections.min(list);
                if(max + min <= limit){
                    list.remove(Integer.valueOf(min));
                }
            }
            answer++;
        }
        
        return answer;
    }
}

 

간단하게 방문체크배열을 새로 생성해서 진행하면 통과할 수 있다.

import java.util.*;

class Solution{

	public int solution(int[] people, int limit){
    
    	int answer = 0; //사용된 구명 보트 개수
        int lightIndex = 0; //가벼운 사람 인덱스
        boolean[] visited = new boolean[people.length]; //방문 ㅔ크
        Arrays.sort(people); //오름차순 정렬
        
        for(int i=people.length - 1 ; i >= 0; i--){
        	if(visited[i] == true) continue;
            
            if(people[i] + people[lightIndex] <= limit){
            	visited[i] = true;
                visited[lightIndex] = true;
                lightIndex++;
                answer++;
            }else{
            	visited[i] = true;
                answer++;
            }
        
        }
        return answer;
    }


}
반응형

댓글