https://www.acmicpc.net/problem/28353
28353번: 고양이 카페
첫째 줄에 정수 $N$과 $K$가 공백으로 구분되어 주어진다. $(1 \leq N \leq 5\,000;$ $1 \leq K \leq 10^9)$ 둘째 줄에는 각 고양이의 무게를 의미하는 $N$개의 정수 $w_1, w_2, \dotsm, w_N$이 공백으로 구분되어 주어
www.acmicpc.net
저는 투포인트를 이용해 문제를 해결하였습니다.
먼저 입력으로 들어오는 고양이들의 무게를 오름차순으로 정렬하고, 시작 지점 과 끝 지점부터 해당 무게를 더하고 이 값이 k보다 크다면, 끝 지점을 하나 줄이고, 같거나 작다면 시작지점을 늘리면서 끝지점을 늘리고 결과값을 하나 늘렸습니다.
이렇게 k보다 작은 두개의 합의 최대 개수를 구하여 문제를 해결하였습니다.
package BOJ.twopoint;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.function.Function;
public class BOJ_28353 {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
Function<String,Integer> stoi = Integer::parseInt;
int n = stoi.apply(st.nextToken());
int k = stoi.apply(st.nextToken());
int[] weight = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < n ; i++){
weight[i] = stoi.apply(st.nextToken());
}
Arrays.sort(weight);
int result = countHappyPeople(weight,n,k);
System.out.println(result);
}
private static int countHappyPeople(int[] weight, int n, int k) {
int startIndex = 0;
int endIndex = n-1;
int cnt = 0;
while(startIndex < endIndex){
int sumWeight = weight[startIndex] + weight[endIndex];
if(sumWeight > k){
endIndex--;
continue;
}
cnt++;
startIndex++;
endIndex--;
}
return cnt;
}
}
'알고리즘' 카테고리의 다른 글
백준 1744번 수 묶기 (JAVA) (0) | 2023.09.05 |
---|---|
백준 29160번 나의 FIFA 팀 가치는? (JAVA) (1) | 2023.09.04 |
백준 25195번 Yes or yes (JAVA) (0) | 2023.09.02 |
백준 11726번 2Xn타일링 (JAVA) (0) | 2023.09.01 |
백준 10917번 Your life (JAVA) (0) | 2023.08.31 |