고양이 수와 무게를 차례대로 입력받고, 고양이 무게를 리스트에 담았습니다.
리스트를 오름차순으로 정렬한 후, 리스트의 맨 앞의 값을 min, 맨 뒤의 값을 max로 설정하였습니다.
각각의 min, max의 index도 0과 size-1로 설정하였고,
minIndex가 maxIndex보다 같거나 커질때까지 반복하였습니다.
min과 max값을 담을 변수를 temp로 설정하고, 만약 temp가 maxWeight보다 크다면, max값을 maxIndex에서 1이 줄어든 값을 가져와서 다시 설정합니다.
만약 temp가 maxWeight보다 작거나 같다면, answer값을 1증가시키고,
min을 array에서의 다음 값으로, max 또한 array에서 하나 줄어든 값으로 설정합니다.
ex) 2 3 4 5 6 7 9 가 있는 list에서 maxWeight=10 인 상황이라면,
step 1) 2 + 9 > 10 이므로, max값인 9를 7로 업데이트
step 2) 2 + 7 < 10 이므로, answer을 1 증가시키면서, min값과 max값을 각각 3과 6으로 업데이트
step 3) 3 + 6 < 10 이므로, answer을 1 증가시키면서, min값과 max값을 각각 4와 5로 업데이트
package Greedy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class BOJ28353 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int cat = scanner.nextInt(); // 고양이 수
int maxWeight = scanner.nextInt(); // 고양이 무게
ArrayList<Integer> arrayList = new ArrayList<>(); // 고양이 무게를 입력받을 리스트
for(int i = 0; i<cat; i++) {
arrayList.add(scanner.nextInt());
}
Collections.sort(arrayList);
int answer = 0;
int min = arrayList.get(0);
int max = arrayList.get(arrayList.size()-1);
int minIndex = 0;
int maxIndex = arrayList.size()-1;
while(minIndex < maxIndex) {
int temp = min+max;
if(temp > maxWeight) {
max = arrayList.get(maxIndex--);
}
else {
answer++;
min = arrayList.get(minIndex++);
max = arrayList.get(maxIndex--);
}
}
System.out.println(answer);
}
}