본문 바로가기
Dev/Algorithm

[프로그래머스] 과일 장수 - Java

by VIPeveloper 2024. 5. 24.
반응형

문제

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

 

프로그래머스

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

programmers.co.kr

 

생각

  • 생각을 하고, 구현하는 정도의 수준이 Lv1 이라면, 나는 그정도는 되는 것 같다는 생각이 들었다.
// 1. 해당 과일을 priority queue 에 담는다.
// 2. m 보다 작다면 queue 에서 하나씩 꺼내서 담는다.
// 3. 마지막으로 담는 것 * k 를 answer 에 더한다.

코드

import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(3,4,new int[] {1, 2, 3, 1, 2, 3, 1})); // 2
        System.out.println(solution(4,3,new int[] {4, 1, 2, 2, 4, 4, 4, 4, 1, 2, 4, 2})); // 2
    }
    public static int solution(int k, int m, int[] score) {
        int answer = 0;
        // 1. 해당 과일을 priority queue 에 담는다.
        PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder());
        for (int i = 0; i < score.length; i++) {
            queue.add(score[i]);
        }
        while (true){
            ArrayList<Integer> arr = new ArrayList<>();
            // 2. m 보다 작다면 queue 에서 하나씩 꺼내서 담는다.
            while (arr.size() != m){
                if(queue.size()==0) break;
                arr.add(queue.poll());
            }
            if(arr.size()<m) break;
            // 3. 마지막으로 담는 것 * k 를 answer 에 더한다.
            int i = arr.get(arr.size() - 1) * arr.size();
            answer += i;
        }
        return answer;
    }
}

다른 사람 풀이

  • 진짜 깔끔했다... 말이 필요 없는 풀이
  • 담고 꺼내고 할 필요가 없다. 
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        System.out.println(solution(3,4,new int[] {1, 2, 3, 1, 2, 3, 1})); // 2
        System.out.println(solution(4,3,new int[] {4, 1, 2, 2, 4, 4, 4, 4, 1, 2, 4, 2})); // 2
    }
    public static int solution(int k, int m, int[] score) {
        int answer = 0;

        Arrays.sort(score);

        for(int i = score.length; i >= m; i -= m){
            answer += score[i - m] * m;
        }

        return answer;
    }
}
반응형