[Greedy] 구명보트

김우진·2022년 10월 12일
0

알고리즘 문제

목록 보기
21/21
post-thumbnail

구명보트

문제 정보

  • 사이트 : 프로그래머스 사이트
  • 문제 번호 : 42885
  • 문제 분류 : Greedy
  • 난이도 : level 2

문제 풀이

내가 짠 코드

💭 생각 노트

  • 몸무게를 기준으로 정렬한 후 한 구명 보트에 2명씩 탈수 있으므로 가장 적은 몸무게와 가장 많은 몸무게를 가진 사람을 짝지어 태운다
  • 처음엔 이중 for문으로 풀었는데 시간초과가 나서 two pointer를 이용해서 풀었다.
import java.util.Arrays;

class Solution {
    public int solution(int[] people, int limit) {
        int answer;
        int count = 0;
        Arrays.sort(people);
        int left = 0;
        int right = people.length-1;
        while (left < right){
            if(people[right] > limit || people[left] + people[right] > limit) {
                count++;
                right--;
            } else {
                left++;
                right--;
                count++;
            }
            if(left == right){
                count++;
                break;
            }
        }
        answer = count;
        return answer;
    }
}

문제 출처

썸네일 출처

Image by storyset on Freepik

0개의 댓글