Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4f541e8

Browse files
committed
O(nlogn) time and O(n) space using min heap
1 parent e474eec commit 4f541e8

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
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.
3+
4+
Return the maximum product of nums after at most k operations. Since the answer may be very large, return it modulo 109 + 7.
5+
6+
7+
8+
Example 1:
9+
10+
Input: nums = [0,4], k = 5
11+
Output: 20
12+
Explanation: Increment the first number 5 times.
13+
Now nums = [5, 4], with a product of 5 * 4 = 20.
14+
It can be shown that 20 is maximum product possible, so we return 20.
15+
Note that there may be other ways to increment nums to have the maximum product.
16+
Example 2:
17+
18+
Input: nums = [6,3,3,2], k = 2
19+
Output: 216
20+
Explanation: Increment the second number 1 time and increment the fourth number 1 time.
21+
Now nums = [6, 4, 3, 3], with a product of 6 * 4 * 3 * 3 = 216.
22+
It can be shown that 216 is maximum product possible, so we return 216.
23+
Note that there may be other ways to increment nums to have the maximum product.
24+
25+
26+
Constraints:
27+
28+
1 <= nums.length, k <= 105
29+
0 <= nums[i] <= 106
30+
"""
31+
class Solution:
32+
def maximumProduct(self, nums: List[int], k: int) -> int:
33+
if len(nums) == 1: return nums[0] + k
34+
min_heap = nums
35+
heapq.heapify(min_heap)
36+
while k > 0:
37+
current = heapq.heappop(min_heap)
38+
cur_diff = min_heap[0] - current
39+
if cur_diff == 0:
40+
current += 1
41+
k -= 1
42+
elif cur_diff > k:
43+
current += k
44+
k = 0
45+
else:
46+
current += cur_diff
47+
k -= cur_diff
48+
heapq.heappush(min_heap,current)
49+
result = 1
50+
while len(min_heap) > 0:
51+
cur = heapq.heappop(min_heap)
52+
result = (result * cur) % (10**9+7)
53+
return result

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /