#2233

Maximum Product After K Increments

Medium
ArrayGreedyHeap (Priority Queue)Heap (Priority Queue)Greedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + k log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n + k log n)Space O(n)

The optimal approach uses a priority queue (min-heap) to always increment the smallest number in the array. This ensures that each increment has the maximum possible effect on the product.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a min-heap from the nums array to efficiently access the smallest element.
  2. 2Step 2: For k times, extract the smallest element, increment it by 1, and push it back into the heap.
  3. 3Step 3: After all increments, calculate the product of all elements in the heap.
solution.py13 lines
1# Full working Python code
2import heapq
3
4def maxProduct(nums, k):
5    heapq.heapify(nums)
6    for _ in range(k):
7        smallest = heapq.heappop(nums)
8        smallest += 1
9        heapq.heappush(nums, smallest)
10    product = 1
11    for num in nums:
12        product = (product * num) % (10**9 + 7)
13    return product

Complexity note: The time complexity is dominated by the heap operations, where each increment takes log n time, and we perform this k times. The space complexity is due to storing the heap.

  • 1Always prioritize incrementing the smallest number to maximize the product.
  • 2Using a min-heap allows for efficient retrieval and updating of the smallest element.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.