알고리즘

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

박카스마시며코딩 2022. 9. 11. 20:19

https://school.programmers.co.kr/learn/courses/30/lessons/42885

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

저는 투포인트를 통해 문제를 해결하였습니다.

한 구명보트에 두명 태울 수 있고, limit보다 크면 안되기 때문에 가장 작은 것과 가장 큰 것을 태워보고 안된다면 결과값을 늘리고, 그 다음 큰 애와 비교해 나가면 됩니다. 

투포인트를 통해 가장 작은 것과 가장 큰 것을 합하여 이것이 limit보다 작으면 작은 인덱스는 늘리고, 큰 인덱스는 줄이고, 결과값을 늘렸습니다. 크다면 큰 인덱스만 줄이고 결과값을 늘렸습니다.

 

 

import java.util.*;
class Solution {
    public int solution(int[] people, int limit) {
        int answer = 0;
        Arrays.sort(people);
        int size = people.length;
        int minIndex = 0;
        int maxIndex = size -1;
        while(true){
            if(people[minIndex] + people[maxIndex] <= limit){
                answer++;
                minIndex++;
                maxIndex--;
            }else{
                maxIndex--;
                answer++;
            }
            if(minIndex > maxIndex){
                break;
            }
        }

        return answer;
    }
}