Maximum Total Reward Using Operations II Problem
Description
LeetCode Problem 3181.
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 <= 5 * 10^41 <= rewardValues[i] <= 5 * 10^4
Solution
Approach: Dynamic Programming + Bit Manipulation
Process the distinct values in increasing order. A total j is reachable if it was reachable before, or if j - v was reachable for the current value v and j - v < v (a value can only be taken while the total is below it). Since the values are large, store the reachable totals as the bits of one big integer f, where bit j is 1 when total j is reachable. Adding a value v means: take the lowest v bits of f, shift them left by v, and OR the result into f. The answer is the position of the highest set bit.
Complexity: O(n * M / w) time and O(M / w) space for the bit set, where n is the number of values, M is twice the maximum value and w is the word size.
class Solution:
def maxTotalReward(self, rewardValues: List[int]) -> int:
nums = sorted(set(rewardValues))
f = 1
for v in nums:
f |= (f & ((1 << v) - 1)) << v
return f.bit_length() - 1