[코드트리 조별과제] 스승의 은혜 (정렬)

KSH·2024년 8월 4일
0

스승의 은혜 문제 링크

코드트리에서 위의 문제를 푼 과정을 기록해보도록 하겠습니다!

문제는 정렬 문제였습니다!

코드 Flow는 다음과 같습니다.
1. 선물 가격과 배송비를 합한 sumPrices 배열 초기화
2. 해당 sumPrices 정렬
3. 순차적으로 sumPrices를 돌면서 sum에 요소들을 더해가고, 예산보다 초과했을 때의 인덱스 저장(overIdx)
4. 해당 overIdx에 해당하는 상품 가격의 반과 배송비를 sum에 더해서 예산과 비교
-> 작으면 해당 인덱스 + 1이 최대 명수, 크면 해당 인덱스가 최대 명수

위의 과정으로 구현하게 됐습니다.
아래는 전체 코드입니다!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer input = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(input.nextToken());
        int B = Integer.parseInt(input.nextToken());

        int[][] prices = new int[N][2];
        int[] sumPrices = new int[N];
        for (int i = 0; i < N; i++) {
            StringTokenizer priceInput = new StringTokenizer(br.readLine());
            int P = Integer.parseInt(priceInput.nextToken());
            int S = Integer.parseInt(priceInput.nextToken());
            prices[i][0] = P;
            prices[i][1] = S;
            sumPrices[i] = P + S;
        }

        Arrays.sort(sumPrices);

        int overIdx = Integer.MAX_VALUE;
        int sum = 0;
        for (int i = 0; i < N; i++) {
            if (sum + sumPrices[i] > B) {
                overIdx = i;
                break;
            }
            sum += sumPrices[i];
        }

        if (overIdx == Integer.MAX_VALUE) {
            System.out.println(N);
        } else {
            int discountP = prices[overIdx][0] / 2;
            int S = prices[overIdx][1];
            if (sum + (discountP + S) <= B) {
                System.out.println(overIdx + 1);
            } else {
                System.out.println(overIdx);
            }
        }
    }
}
profile
성실히 살아가는 비전공자

0개의 댓글