학생수와 예산의 수가 주어지고,
학생 수 만큼 각각 물건 값과 배송비가 주어진다.
물건 값을 반으로 할인받을 수 있는 할인쿠폰이 존재할때
최대로 선물할 수 있는 학생의 수는 ?
4 2
1 3
2 3
2 2
0 1
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int money = sc.nextInt();
int[][] lst = new int[n][3];
for (int i = 0; i < n; i++) {
lst[i][0] = sc.nextInt() / 2; // 가격
lst[i][1] = sc.nextInt(); // 추가 비용
lst[i][2] = lst[i][0] + lst[i][1]; // 총 비용
}
Arrays.sort(lst, (a, b) -> {
if (a[2] != b[2]) {
return Integer.compare(a[2], b[2]); // 총 비용 기준 오름차순
} else {
return Integer.compare(b[0], a[0]); // 가격 기준 내림차순
}
});
boolean usedDiscount = false; // 할인 사용 여부
int sum = 0; // 현재 총 비용
int count = 0; // 구매 가능한 아이템 개수
for (int i = 0; i < n; i++) {
int price = lst[i][0];
int additionalCost = lst[i][1];
int totalCost = price * 2 + additionalCost;
if (!usedDiscount && sum + price + additionalCost <= money) {
// 할인 적용 가능한 경우
sum += (price / 2) + additionalCost;
usedDiscount = true;
count++;
} else if (sum + totalCost <= money) {
// 할인 없이 구매 가능한 경우
sum += totalCost;
count++;
} else {
// 더 이상 구매 불가
break;
}
}
System.out.println(count);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int money = sc.nextInt();
int[][] lst = new int[n][3];
for (int i = 0; i < n; i++) {
lst[i][0] = sc.nextInt(); // 원래 가격
lst[i][1] = sc.nextInt(); // 추가 비용
lst[i][2] = lst[i][0] + lst[i][1]; // 총 비용
}
// 총 비용 기준 오름차순 정렬
Arrays.sort(lst, (a, b) -> Integer.compare(a[2], b[2]));
int maxCount = 0;
// 모든 아이템에 대해 한 번씩 할인 적용
for (int i = 0; i < n; i++) {
int remainingMoney = money - (lst[i][0] / 2 + lst[i][1]); // i번 아이템 할인 적용
if (remainingMoney < 0) continue; // 할인 적용해도 예산 초과 시 건너뜀
int count = 1; // 할인 적용한 아이템 포함
for (int j = 0; j < n; j++) {
if (i == j) continue; // 할인 적용한 아이템은 제외
if (remainingMoney >= lst[j][2]) {
remainingMoney -= lst[j][2];
count++;
} else {
break;
}
}
maxCount = Math.max(maxCount, count); // 최대 구매 가능 개수 갱신
}
System.out.println(maxCount);
}
}
완전탐색으로 해결..
https://www.codetree.ai/trails/complete/curated-cards/test-the-grace-form-teacher-3/description