LeetCode 题解工作台
执行操作可获得的最大总奖励 I
给你一个整数数组 rewardValues ,长度为 n ,代表奖励的值。 最初,你的总奖励 x 为 0,所有下标都是 未标记 的。你可以执行以下操作 任意次 : 从区间 [0, n - 1] 中选择一个 未标记 的下标 i 。 如果 rewardValues[i] 大于 你当前的总奖励 x ,则将…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们可以对奖励值数组 `rewardValues` 进行排序,然后使用记忆化搜索的方法求解最大总奖励。 我们定义一个函数 ,表示当前总奖励为 时,能够获得的最大总奖励。那么答案为 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个整数数组 rewardValues,长度为 n,代表奖励的值。
最初,你的总奖励 x 为 0,所有下标都是 未标记 的。你可以执行以下操作 任意次 :
- 从区间
[0, n - 1]中选择一个 未标记 的下标i。 - 如果
rewardValues[i]大于 你当前的总奖励x,则将rewardValues[i]加到x上(即x = x + rewardValues[i]),并 标记 下标i。
以整数形式返回执行最优操作能够获得的 最大 总奖励。
示例 1:
输入:rewardValues = [1,1,3,3]
输出:4
解释:
依次标记下标 0 和 2,总奖励为 4,这是可获得的最大值。
示例 2:
输入:rewardValues = [1,6,4,3,2]
输出:11
解释:
依次标记下标 0、2 和 1。总奖励为 11,这是可获得的最大值。
提示:
1 <= rewardValues.length <= 20001 <= rewardValues[i] <= 2000
解题思路
方法一:排序 + 记忆化搜索 + 二分查找
我们可以对奖励值数组 rewardValues 进行排序,然后使用记忆化搜索的方法求解最大总奖励。
我们定义一个函数 ,表示当前总奖励为 时,能够获得的最大总奖励。那么答案为 。
函数 的执行过程如下:
- 二分查找数组
rewardValues中第一个大于 的元素的下标 ; - 遍历数组
rewardValues中从下标 开始的元素,对于每个元素 ,计算 的最大值。 - 将结果返回。
为了避免重复计算,我们使用记忆化数组 f 记录已经计算过的结果。
时间复杂度 ,空间复杂度 。其中 是数组 rewardValues 的长度,而 是数组 rewardValues 中的最大值的两倍。
class Solution:
def maxTotalReward(self, rewardValues: List[int]) -> int:
@cache
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)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on how the state transitions are computed, typically O(n^2) in naive DP or O(n log n) with optimizations. Space complexity depends on the DP table size, usually O(n) for a 1D table, reflecting the reward states at each index. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Watch for proper DP initialization and edge cases when indices are at the array boundaries.
- question_mark
Prioritize understanding how each operation affects subsequent states to avoid overcounting rewards.
- question_mark
Explain your reasoning for sorting or not sorting the array as it directly impacts transition correctness.
常见陷阱
外企场景- error
Ignoring the effect of previous operations on future state transitions, leading to suboptimal total rewards.
- error
Incorrectly updating DP states, which can either double-count rewards or miss valid sequences.
- error
Not handling edge indices properly, which can cause array out-of-bounds errors or wrong maximum computation.
进阶变体
外企场景- arrow_right_alt
Limit the number of operations allowed and compute maximum reward under operation constraints.
- arrow_right_alt
Include negative reward values to test state transition handling with mixed contributions.
- arrow_right_alt
Extend to multi-dimensional reward arrays, requiring more complex DP state tracking.