2233. Maximum Product After K Increments
2233. Maximum Product After K Increments
1 | You are given an array of non-negative integers nums and an integer k. In one operation, |
难度 : Medium
Solution
Use PriorityQueue. Put all the nums to the PriorityQueue.
For each operation, take out the min value x, and put (x+1) back to the queue.
Proof:1
2
3
4
5
6
7For example, there are 2 nums x and y
if increase x, then the product is
(x + 1) * y = x * y + y
if increase y, then the product is
(y + 1) * x = x * y + x
if x < y then (x*y) + y > (x*y) +x
Time Complexity : O(K logN + N logN)
Space Complexity: O(N)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19class Solution {
private static final int MOD = (int)1e9 + 7;
public int maximumProduct(int[] nums, int k) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
for (int num : nums) {
pq.offer(num);
}
while (k-- > 0) {
int min = pq.poll();
pq.offer(min + 1);
}
long ans = 1;
while (!pq.isEmpty()) {
ans *= pq.poll();
ans %= MOD;
}
return (int) ans;
}
}