Maximum Product After K Increments - Problem

You are given an array of non-negative integers nums and an integer k. In one operation, you may choose any element from nums and increment it by 1.

Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7.

Note that you should maximize the product before taking the modulo.

Input & Output

Example 1 — Basic Case
$ Input: nums = [0,4], k = 5
Output: 20
💡 Note: Increment the first element 5 times: [0,4] → [5,4]. Product = 5 × 4 = 20.
Example 2 — Multiple Small Elements
$ Input: nums = [6,3,3,2], k = 2
Output: 216
💡 Note: Increment smallest elements: [6,3,3,2] → [6,3,3,3] → [6,3,4,3]. Product = 6 × 3 × 4 × 3 = 216.
Example 3 — Zero in Array
$ Input: nums = [1,0,1], k = 1
Output: 1
💡 Note: Increment the zero: [1,0,1] → [1,1,1]. Product = 1 × 1 × 1 = 1.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 106
  • 1 ≤ k ≤ 106

Visualization

Tap to expand
Maximum Product After K Increments INPUT Array nums: 0 index 0 4 index 1 Operations allowed: k = 5 Each operation: Pick any element Increment by 1 nums=[0,4], k=5 ALGORITHM STEPS 1 Build Min-Heap Push all nums to heap 0 4 2 Repeat k times: Pop min, add 1, push back 3 Simulation: k=5: [0,4] pop 0 --> [1,4] k=4: [1,4] pop 1 --> [2,4] k=3: [2,4] pop 2 --> [3,4] k=2: [3,4] pop 3 --> [4,4] k=1: [4,4] pop 4 --> [4,5] 4 Compute Product Multiply all elements Final: [4, 5] FINAL RESULT Optimized Array: 4 5 x 20 OK - Maximum Product! 4 x 5 = 20 All 5 operations used Values balanced for max Output: 20 Key Insight: To maximize product, always increment the SMALLEST element. Using a min-heap ensures O(log n) access to minimum. Balanced values yield higher products: (3x3=9) is greater than (1x5=5). TutorialsPoint - Maximum Product After K Increments | Greedy with Priority Queue
Asked in
Google 12 Amazon 8 Microsoft 6 Apple 4
12.5K Views
Medium Frequency
~25 min Avg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen