LeetCode 2233. K 次增加后的最大乘积

2233. K 次增加后的最大乘积

 

【贪心 + 计数】这道题的数据范围就可以用数组来统计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; 
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值