每次都给数组里最小的数加一,这样相乘起来的积最大
解法一:优先级队列,取出一个数加一然后放回,重复K次
public int maximumProduct2(int[] nums, int k) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
for (int num : nums) {
queue.add(num);
}
for (int i = 0; i < k; i++) {
int a = queue.poll();
a++;
queue.add(a);
}
long res = 1;
while (!queue.isEmpty()) {
int b = queue.poll();
res = (res * b) % 1000000007;
}
return (int) res;
}
解法二:Map + 贪心(效率更高)
先把所有数出现的次数和最小值存起来,然后比较K和最小值出现的次数count
①K >= count
移除map中的最小值key,给key+1的value增加count,K = K -count
②K < count
在map中新增K个key+1,然后key的value - K
public int maximumProduct(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
int min = Integer.MAX_VALUE;
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
min = min < num ? min : num;
}
while (k > 0) {
int count = map.get(min);
if (count >= k) {
map.put(min + 1, map.getOrDefault(min + 1, 0) + k);
map.put(min, count - k);
k = 0;
} else {
map.put(min + 1, map.getOrDefault(min + 1, 0) + count);
map.remove(min);
k -= count;
min++;
}
}
long res = 1;
for (Integer integer : map.keySet()) {
for (Integer i = 0; i < map.get(integer); i++) {
res = (res * integer) % 1000000007;
}
}
return (int) res;
}