#1648
Sell Diminishing-Valued Colored Balls
MediumArrayMathBinary SearchGreedySortingHeap (Priority Queue)HeapGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n + orders log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n + orders log n)Space O(n)
The optimal solution uses a greedy approach combined with a priority queue (max-heap) to efficiently sell the highest valued balls first while keeping track of the remaining orders. This significantly reduces the time complexity.
⚙️
Algorithm
4 steps- 1Step 1: Use a max-heap to store the inventory counts.
- 2Step 2: While there are orders to fulfill, extract the maximum value from the heap.
- 3Step 3: Calculate how many balls can be sold at that value and update the total value accordingly.
- 4Step 4: If there are remaining balls of that value, push the new value back into the heap.
solution.py13 lines
1import heapq
2
3def maxProfit(inventory, orders):
4 inventory = [-x for x in inventory]
5 heapq.heapify(inventory)
6 total_value = 0
7 while orders > 0:
8 max_value = -heapq.heappop(inventory)
9 total_value += max_value
10 orders -= 1
11 if max_value - 1 > 0:
12 heapq.heappush(inventory, -(max_value - 1))
13 return total_value % (10**9 + 7)ℹ
Complexity note: The complexity is O(n log n) for building the max-heap and O(orders log n) for processing each order, making it efficient for larger inputs.
- 1Greedily sell the highest valued balls first.
- 2Using a max-heap allows efficient retrieval of the maximum value.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.