PS

Leetcode 2233. Maximum Product After K Increments

Bryan Lee 2022. 4. 24. 23:22

문제 이해

- 배열에 있는 값들을 +1씩 K번 증가할 때,  

  최종적으로 배열에 있는 값들의 곱을 최대화할 수 있도록 하라 

 

해결 전략

- 우선순위 큐를 사용해서, 배열의 값들을 저장한다.

- 우선순위 큐를 통해, 가장 작은 값을 추출하고, 그 값에 1을 더한 후, 

   다시 우선순위 큐에 넣는다.

- 우선순위 큐에서 값을 하나씩 빼면서 곱해준다. 

 

구현

class Solution {
     public int maximumProduct(int[] nums, int k) {
        
        long answer = 1; 
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        
        for(int i=0; i<nums.length; i++){
            pq.add(nums[i]);
        }
        
        int cnt = 0; 
        
        while(true){
            
            if(cnt == k){
                break; 
            }
            
            int num = pq.poll();
            num += 1;
            pq.add(num);
            cnt += 1;
        }
        
        while(true){
            
            if(pq.isEmpty()){
                break; 
            }
            
            int num = pq.poll();
            answer = (answer*num) % 1000000007;
        }
        
        
        return (int)answer; 
        
        
     }
}

 

피드백

- answer에 값을 곱할 때, 하나씩 곱할때마다 10의9승+7의 값으로 모듈로 연산을 해야 한다. 

- answer를 long으로 선언하고, 나중에 return 할 때 int로 변환해야 한다.