프로그래머스 - 다단계 칫솔 판매

최지홍·2022년 4월 2일
0

프로그래머스

목록 보기
14/15

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


import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int[] solution(String[] enroll, String[] referral, String[] seller, int[] amount) {
        // 사람별 번호 부여
        Map<String, Integer> people = new HashMap<>();
        for (int i = 0; i < enroll.length; i++) {
            people.put(enroll[i], i);
        }

        // 부모 노드와 매칭
        Map<String, String> parents = new HashMap<>();
        for (int i = 0; i < referral.length; i++) {
            parents.put(enroll[i], referral[i]);
        }

        // 이익 누적 배열
        int[] profits = new int[enroll.length];

        for (int i = 0; i < seller.length; i++) {
            String person = seller[i];
            int profit = amount[i] * 100;

            while (true) {
                int tenPercent = (int) (profit * 0.1);

                // 현재 자신 처리
                if (tenPercent >= 1) {
                    profits[people.get(person)] += (profit - tenPercent);
                } else {
                    profits[people.get(person)] += profit;
                    break;
                }

                if ((parents.get(person)).equals("-")) break;

                person = parents.get(person);
                profit = tenPercent;
            }
        }
        
        return profits;
    }
}

  • 사람별로 번호를 부여하여 사람별로 이익을 저장할 수 있도록 하였다.
  • 먼저 현재 사람의 이익을 계산하고, 더이상 부모가 없을 때까지 상위 노드로 이동하면서 값을 업데이트해준다. 10%가 1 미만인 경우에는 부모에 더하지 않고 자신의 이익만 계산하고 끝내고, 계속 가서 더 이상 부모가 없는 경우에도 끝낸다.
profile
백엔드 개발자가 되자!

0개의 댓글

관련 채용 정보