본문으로 바로가기

https://school.programmers.co.kr/learn/courses/30/lessons/150368

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 

 

이모티콘은 10 / 20 / 30 / 40 % 중에 하나 선택하여 할인을 하고 

유저는 n% 이상 할인일 때 해당 이모티콘을 구매한다. 

 

단 이모티콘 구입 도중 유저가 정한 특정 금액을 넘어가면 이모티콘 플러스 가입으로 전환한다. 

 

1순위 이익은 이모티콘 플러스 가입의 최대화 이고

2순위는 이모티콘 매출일 때, 

 

이익이 최대화 될 때 이모티콘 플러스 가입자 수와 이모티콘 판매액을 출력하는 문제 

 


풀이 

이모티콘의 갯수가 많지 않으므로 10 ~ 40 % 사이를 선택하여

dfs 를 통해 풀었다. 

 

처음 풀이할 때 분명 다 맞았는데 3개의 문제에서 실패가 뜨길래 

검색해 봤더니 부동소수점 문제 같더라 ( 가격은 100의 배수여서 문제가 없을거 같은데.. 잘 모르겠다 )

 

그래서 계산하는 부분만 double 로 체크하여 풀었다. 

 

import java.util.Arrays;

class Solution {
    static int totalMax = 0;
    static int plusMax = 0;
    static int[][] USERS;
    static int[] EMOTICONS;
    
    public int[] solution(int[][] users, int[] emoticons) {
        USERS = users;
        EMOTICONS = emoticons;
        
        dfs(0, 0, 0, 10, new int[USERS.length]);
        dfs(0, 0, 0, 20, new int[USERS.length]);
        dfs(0, 0, 0, 30, new int[USERS.length]);
        dfs(0, 0, 0, 40, new int[USERS.length]);
    
        return new int[]{plusMax, totalMax};
    }
    
    public void dfs(int total, int plusCount, int index, int discount, int[] userTotal) {
        if (index >= EMOTICONS.length) {
            if (plusCount > plusMax ) {
                totalMax = total;
                plusMax = plusCount;
            } else if (plusCount == plusMax) {
                totalMax = Math.max(totalMax, total);
            }
            return;
        }
        
        for (int i = 0; i<USERS.length; i++) {
            if (userTotal[i] == -1) {
                continue;
            }
            int nowUser = userTotal[i];
            if (USERS[i][0] <= discount) {
                double discountPrice = EMOTICONS[index] * ((double)(100 - discount) / 100);
                
                if ( nowUser + discountPrice >= USERS[i][1]) {
                    userTotal[i] = -1;
                    plusCount++;
                    total -= nowUser;
                } else {
                    userTotal[i] += discountPrice;
                    total += discountPrice;
                }
            }
        }
        
        dfs(total, plusCount, index+1, 10, Arrays.copyOf(userTotal, userTotal.length));
        dfs(total, plusCount, index+1, 20, Arrays.copyOf(userTotal, userTotal.length));
        dfs(total, plusCount, index+1, 30, Arrays.copyOf(userTotal, userTotal.length));
        dfs(total, plusCount, index+1, 40, Arrays.copyOf(userTotal, userTotal.length));
    }
}