[알고리즘] 한빈이와 Spot Mart
2024. 2. 5. 15:43ㆍ알고리즘 풀이/Java
https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AW8Wj7cqbY0DFAXN
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class Solution {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int T = Integer.parseInt(st.nextToken());
for (int testCase = 1; testCase <= T; testCase++) {
st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] snacks = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
snacks[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(snacks);
sb.append("#").append(testCase).append(" ");
int maxWeight = Integer.MIN_VALUE;
int start = 0;
int end = N-1;
out: while (start < end) {
int sumWeight = snacks[start] + snacks[end];
if (sumWeight > M) {
end--;
} else if (sumWeight == M) {
maxWeight = M;
break out;
} else {
maxWeight = Math.max(maxWeight, sumWeight);
start++;
}
}
if (maxWeight == Integer.MIN_VALUE) {
maxWeight = -1;
}
sb.append(maxWeight).append("\n");
}
System.out.println(sb);
}
}
나의 풀이
- 이중 포인터를 활용하면 되는 문제
- start와 end가 같아질 때까지 while 조건문을 설정해주면 된다.
- start++인데 start--라고 적는 실수를 했었다.
'알고리즘 풀이 > Java' 카테고리의 다른 글
[알고리즘][X] AC (1) | 2024.02.06 |
---|---|
[알고리즘] 요세푸스 문제 (0) | 2024.02.05 |
[알고리즘] 수열 편집 (1) | 2024.02.05 |
[알고리즘] 암호문3 (0) | 2024.02.02 |
[알고리즘] 암호생성기 (0) | 2024.02.02 |