Maximum Product After K Increments — LeetCode 2233 Python Solution
MediumGreedyArrayHeap (Priority Queue)
- Problem
- #2233
- Pattern
- Heap / Priority Queue
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- nums = [0,4], k = 5
- Output
- 20
- Explanation
- Increment the first number 5 times.
Python solution
Python
class Solution:
def maximumProduct(self, nums: List[int], k: int) -> int:
heapify(nums)
for _ in range(k):
heapreplace(nums, nums[0] + 1)
mod = 10**9 + 7
return reduce(lambda x, y: x * y % mod, nums)Complexity
| Measure | Complexity |
|---|---|
| Time | O(k \times \log n) |
| Space | O(n) auxiliary |
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 2233. Maximum Product After K Increments is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2233. Maximum Product After K Increments?
- LeetCode 2233. Maximum Product After K Increments is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2233. Maximum Product After K Increments?
- The Python solution on this page runs in O(k \times \log n).
- What is the space complexity of LeetCode 2233. Maximum Product After K Increments?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2233. Maximum Product After K Increments cover?
- LeetCode 2233. Maximum Product After K Increments is tagged Greedy, Array and Heap (Priority Queue) on LeetCode.