Maximum Product After K Increments

With k +1 operations, maximize the product — always increment the current smallest via a min-heap.

Medium
Time O((n + k) log n) Space O(n)
LeetCode
5 min read
top-k heaps greedy

Problem#

You may perform k increments (each +1 to any element). Return the maximum product modulo 10⁹ + 7.

Examples#

  • nums = [0,4], k = 520 ([2,3])
  • nums = [6,3,3,2], k = 2216 ([6,3,3,4])

Constraints#

  • 1 <= nums.length, k <= 10^5.

Approach#

To maximize a product, equalize — increment the smallest element each step. Min-heap, pop k times, push back +1.

Solution#

Maximum Product After K Increments
class Solution {
public:
int maximumProduct(vector<int>& nums, int k) {
const int MOD = 1'000'000'007;
priority_queue<int, vector<int>, greater<int>> pq(nums.begin(), nums.end());
while (k--) {
int x = pq.top(); pq.pop();
pq.push(x + 1);
}
long long prod = 1;
while (!pq.empty()) {
prod = (prod * pq.top()) % MOD;
pq.pop();
}
return (int)prod;
}
};

Editorial#

AM-GM intuition: equal terms maximize the product for a fixed sum. Incrementing the smallest at each step monotonically balances the values, which is the discrete approximation to AM-GM optimality.

Complexity#

  • Time: O((n + k) log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.