알고리즘 풀이/프로그래머스

[프로그래머스][JAVA] 구명보트 (그리디)

배게 2022. 4. 3. 13:56
728x90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.*;
 
class Solution {
    public int solution(int[] people, int limit) {
        Arrays.sort(people);
        // System.out.println(people[0]);
        
        int answer = 0;
        int i = 0;
        int j = people.length-1;
        while(i<=j){
            if(i==j){
                answer++;
                break;
            }
            else{
                if(people[i]+people[j]<=limit){
                    i++;
                    j--;
                    answer++;
                }
                else{
                    j--;
                    answer++;
                }  
            }           
        }
        
        
        return answer;
    }
}
cs