Maximum Total Reward Using Operations I Problem
Description
LeetCode Problem 3180.
You are given an integer array rewardValues of length n, representing the values of rewards.
Initially, your total reward x is 0, and all indices are unmarked. You are allowed to perform the following operation any number of times:
- Choose an unmarked index
ifrom the range[0, n - 1]. - If
rewardValues[i]is greater than your current total rewardx, then addrewardValues[i]tox(i.e.,x = x + rewardValues[i]), and mark the indexi.
Return an integer denoting the maximum total reward you can collect by performing the operations optimally.
Example 1:
Input: rewardValues = [1,1,3,3]
Output: 4
Explanation:
During the operations, we can choose to mark the indices 0 and 2 in order, and the total reward will be 4, which is the maximum.
Example 2:
Input: rewardValues = [1,6,4,3,2]
Output: 11
Explanation:
Mark the indices 0, 2, and 1 in order. The total reward will then be 11, which is the maximum.
Constraints:
1 <= rewardValues.length <= 20001 <= rewardValues[i] <= 2000
Solution
Approach: Sorting + Memoization + Binary Search
Sort rewardValues. Let dfs(x) be the largest reward we can still collect when the current total is x; the answer is dfs(0). Only values greater than x may be taken, so binary search for the first such index i, then try every value v from i on and keep the maximum of v + dfs(x + v). Results are cached in an array indexed by x.
Complexity: O(n * (log n + M)) time and O(M) space, where n is the length of rewardValues and M is twice its maximum.
from bisect import bisect_right
from functools import lru_cache
class Solution:
def maxTotalReward(self, rewardValues: List[int]) -> int:
@lru_cache(None)
def dfs(x: int) -> int:
i = bisect_right(rewardValues, x)
ans = 0
for v in rewardValues[i:]:
ans = max(ans, v + dfs(x + v))
return ans
rewardValues.sort()
return dfs(0)