231117 다단계 칫솔 판매

Jongleee·2023년 11월 17일
0

TIL

목록 보기
419/737
public int[] solution(String[] enroll, String[] referral, String[] seller, int[] amount) {
	int[] answer = new int[enroll.length];
	Map<String, String> parent = new HashMap<>();
	Map<String, Integer> memberIndex = new HashMap<>();

	initializeMaps(enroll, referral, parent, memberIndex);

	calculateProfitsForSellers(seller, amount, answer, parent, memberIndex);

	return answer;
}

private void initializeMaps(String[] enroll, String[] referral, Map<String, String> parent,
		Map<String, Integer> memberIndex) {
	for (int i = 0; i < enroll.length; i++) {
		parent.put(enroll[i], referral[i]);
		memberIndex.put(enroll[i], i);
	}
}

private void calculateProfitsForSellers(String[] seller, int[] amount, int[] answer, Map<String, String> parent,
		Map<String, Integer> memberIndex) {
	for (int i = 0; i < seller.length; i++) {
		String currentSeller = seller[i];
		int profit = 100 * amount[i];

		while (!currentSeller.equals("-")) {
			int parentProfit = profit / 10;
			int myProfit = profit - parentProfit;
			answer[memberIndex.get(currentSeller)] += myProfit;
			currentSeller = parent.get(currentSeller);
			profit /= 10;
			if (profit < 1) {
				break;
			}
		}
	}
}

출처:https://school.programmers.co.kr/learn/courses/30/lessons/77486

0개의 댓글