Maximum Total Sum with Threshold Constraints Problem
Description
LeetCode Problem 3763.
You are given two integer arrays nums and threshold, both of length n.
Starting at step = 1, you perform the following repeatedly:
- Choose an unused index
isuch thatthreshold[i] <= step.- If no such index exists, the process ends.
- Add
nums[i]to your running total. - Mark index
ias used and incrementstepby 1.
Return the maximum total sum you can obtain by choosing indices optimally.
Example 1:
Input: nums = [1,10,4,2,1,6], threshold = [5,1,5,5,2,2]
Output: 17
Explanation:
- At step = 1, choose i = 1 since threshold[1] <= step. The total sum becomes 10. Mark index 1.
- At step = 2, choose i = 4 since threshold[4] <= step. The total sum becomes 11. Mark index 4.
- At step = 3, choose i = 5 since threshold[5] <= step. The total sum becomes 17. Mark index 5.
- At step = 4, we cannot choose indices 0, 2, or 3 because their thresholds are > 4, so we end the process.
Example 2:
Input: nums = [4,1,5,2,3], threshold = [3,3,2,3,3]
Output: 0
Explanation:
At step = 1 there is no index i with threshold[i] <= 1, so the process ends immediately. Thus, the total sum is 0.
Example 3:
Input: nums = [2,6,10,13], threshold = [2,1,1,1]
Output: 31
Explanation:
- At step = 1, choose i = 3 since threshold[3] <= step. The total sum becomes 13. Mark index 3.
- At step = 2, choose i = 2 since threshold[2] <= step. The total sum becomes 23. Mark index 2.
- At step = 3, choose i = 1 since threshold[1] <= step. The total sum becomes 29. Mark index 1.
- At step = 4, choose i = 0 since threshold[0] <= step. The total sum becomes 31. Mark index 0.
- After step = 4 all indices have been chosen, so the process ends.
Constraints:
n == nums.length == threshold.length1 <= n <= 10^51 <= nums[i] <= 10^91 <= threshold[i] <= n
Solution
Approach: Greedy with a Max-Heap
At every step we may take any unused index whose threshold is at most the current step, and taking a larger number is never worse: later steps only open more indices, so a choice made now never blocks a better option later. So at each step take the largest available number.
Sort the indices by threshold. Keep a max-heap of the numbers that are available. At each step, push every number whose threshold is at most step into the heap, then pop the largest and add it to the total. If the heap is empty, the process ends.
Complexity: O(n log n) time and O(n) space.
import heapq
class Solution:
def maxSum(self, nums: List[int], threshold: List[int]) -> int:
n = len(nums)
idx = sorted(range(n), key=lambda i: threshold[i])
heap = [] # max-heap by storing negative values
step = 1
ans = i = 0
while True:
while i < n and threshold[idx[i]] <= step:
heapq.heappush(heap, -nums[idx[i]])
i += 1
if not heap:
break
ans -= heapq.heappop(heap)
step += 1
return ans