티스토리 뷰

반응형

https://programmers.co.kr/learn/courses/30/lessons/72411

 

코딩테스트 연습 - 메뉴 리뉴얼

레스토랑을 운영하던 스카피는 코로나19로 인한 불경기를 극복하고자 메뉴를 새로 구성하려고 고민하고 있습니다. 기존에는 단품으로만 제공하던 메뉴를 조합해서 코스요리 형태로 재구성해서

programmers.co.kr

import java.util.*;
class Solution {
    public String[] solution(String[] orders, int[] course) {
        Restaurant restaurant = new Restaurant(orders, course);
        return restaurant.checkCourseMenu().getCandidateMenu();
    }
    public static class Restaurant {
        private static final PriorityQueue<String> pq = new PriorityQueue<>();
        private static Map<String, Integer> map;

        private int maxValue = 0;
        private final String[] orders;
        private final int[] course;

        public Restaurant (String[] orders, int[] course) {
            this.orders = orders;
            this.course = course;
            map = new HashMap<>();

        }

        public String[] getCandidateMenu() {
            String[] ans = new String[pq.size()];
            int k = 0;
            while (!pq.isEmpty()){
                ans[k++] = pq.poll();
            }
            return ans;
        }

        private Restaurant checkCourseMenu() {
            for (int kind : course) {
                map.clear();
                maxValue = 0;
                for(String order : orders) {
                    find(0, "",kind,0,order);
                }
                for (String key : map.keySet()) {
                    if (map.get(key) == maxValue && maxValue > 1){
                        pq.offer(key);
                    }
                }
            }
            return this;
        }


        private void find(int count, String str, int aim, int idx, String order) {
            if (count == aim){
                char[] c = str.toCharArray();
                Arrays.sort(c);
                StringBuilder temps= new StringBuilder();
                for (char value : c) temps.append(value);
                map.put(temps.toString(),map.getOrDefault(temps.toString(),0)+1);
                maxValue = Math.max(maxValue,map.get(temps.toString()));
                return ;
            }
            for (int i=idx; i< order.length(); i++) {
                char food = order.charAt(i);
                find(count+1,str+food,aim,i+1,order);
            }
        }

    }

}

이 문제의 접근 방법은 각 메뉴 갯수에 따른 손님이 주문한 메뉴들에서 조합의 갯수를 카운팅하여 그 중에서 최댓값들을 가진 메뉴들만 우선순위 큐에 저장하고 그에 대한 값을 반환하는 것이다.

 

 

checkCourseMenu

course의 갯수에 따른 각 사람에 따른 order의 최댓 갯수를 우선순위큐에 넣는 함수

 

find

조합의 경우를 만들어서 그에 대한 값을 map에 넣고, 해당 코스에 대한 최댓갑을 구하는 함수다.

 

getCandidateMenu

문제에서 원하는 답의 형태로 바꾸는 함수이다.

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함