【贪心 + 计数】这道题的数据范围就可以用数组来统计nums出现次数了,每次加1就是把nums[i - 1]的个数加到nums[i]上去。
class Solution {
// 贪心 8:14 9
public int maximumProduct(int[] nums, int k) {
int n = (int)1e6 + (int)1e5 + 1;
int mod = (int)1e9 + 7;
int[] cnt = new int[n];
int m = 0;
for (var x: nums) {
cnt[x]++;
if (x == 0) m++;
}
if (m > k) return 0;
long ans = 1;
for (var i = 0; i < n - 1; i++) {
if (cnt[i] == 0) continue;
int c = Math.min(cnt[i], k);
cnt[i] -= c;
cnt[i + 1] += c;
k -= c;
if (k == 0) break;
}
for (var i = 1; i < n; i++) {
for (var j = 0; j < cnt[i]; j++) {
ans = (ans * i) % mod;
}
}
return (int)ans;
}
}
【贪心 + 优先队列】因为k的次数只有10^5,所以用优先队列也能做,O(10^5 * log(10^6))而已。
class Solution {
// 贪心 + 优先队列 8:41
public int maximumProduct(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue();
for (var x: nums) queue.offer(x);
while (k-- > 0) {
queue.offer(queue.poll() + 1);
}
long ans = 1;
int mod = (int)1e9 + 7;
for (var x: queue) ans = (ans * x) % mod;
return (int)ans;
}
}