LeetCode 题解工作台
访问数组中的位置使分数最大
给你一个下标从 0 开始的整数数组 nums 和一个正整数 x 。 你 一开始 在数组的位置 0 处,你可以按照下述规则访问数组中的其他位置: 如果你当前在位置 i ,那么你可以移动到满足 i 的 任意 位置 j 。 对于你访问的位置 i ,你可以获得分数 nums[i] 。 如果你从位置 i 移动…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
根据题目描述,我们可以得到以下结论: 1. 从位置 移动到位置 时,如果 和 的奇偶性不同,那么会损失 分;
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你一个下标从 0 开始的整数数组 nums 和一个正整数 x 。
你 一开始 在数组的位置 0 处,你可以按照下述规则访问数组中的其他位置:
- 如果你当前在位置
i,那么你可以移动到满足i < j的 任意 位置j。 - 对于你访问的位置
i,你可以获得分数nums[i]。 - 如果你从位置
i移动到位置j且nums[i]和nums[j]的 奇偶性 不同,那么你将失去分数x。
请你返回你能得到的 最大 得分之和。
注意 ,你一开始的分数为 nums[0] 。
示例 1:
输入:nums = [2,3,6,1,9,2], x = 5 输出:13 解释:我们可以按顺序访问数组中的位置:0 -> 2 -> 3 -> 4 。 对应位置的值为 2 ,6 ,1 和 9 。因为 6 和 1 的奇偶性不同,所以下标从 2 -> 3 让你失去 x = 5 分。 总得分为:2 + 6 + 1 + 9 - 5 = 13 。
示例 2:
输入:nums = [2,4,6,8], x = 3 输出:20 解释:数组中的所有元素奇偶性都一样,所以我们可以将每个元素都访问一次,而且不会失去任何分数。 总得分为:2 + 4 + 6 + 8 = 20 。
提示:
2 <= nums.length <= 1051 <= nums[i], x <= 106
解题思路
方法一:动态规划
根据题目描述,我们可以得到以下结论:
- 从位置 移动到位置 时,如果 和 的奇偶性不同,那么会损失 分;
- 从位置 移动到位置 时,如果 和 的奇偶性相同,那么不会损失分数。
因此,我们可以用一个长度为 的数组 来表示当前位置的奇偶性为 和 时的最大得分。初始时 的值为 ,然后我们再初始化 ,表示初始位置的得分。
接下来,我们从位置 开始遍历数组 ,对于每个位置 对应的值 ,我们更新 的值为 和 的较大值再加上 ,即 。
答案为 和 中的较大值。
时间复杂度 ,其中 为数组 的长度。空间复杂度 。
class Solution:
def maxScore(self, nums: List[int], x: int) -> int:
f = [-inf] * 2
f[nums[0] & 1] = nums[0]
for v in nums[1:]:
f[v & 1] = max(f[v & 1], f[v & 1 ^ 1] - x) + v
return max(f)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the DP implementation. A naive approach is O(n^2) by checking all previous indices. Space complexity is O(n) to store the DP array. Optimizations using monotonic queues or parity tracking can reduce redundant calculations. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you tracking maximum scores separately for even and odd parity transitions?
- question_mark
Can you optimize DP transitions to avoid O(n^2) iteration over all previous indices?
- question_mark
How do you handle penalties when moving between numbers of different parity?
常见陷阱
外企场景- error
Forgetting to subtract x for parity changes between consecutive positions.
- error
Assuming all moves contribute positively without checking parity penalties.
- error
Overlooking the need to track separate maximum scores for even and odd parity states.
进阶变体
外企场景- arrow_right_alt
Penalty depends on the difference between numbers instead of fixed x.
- arrow_right_alt
Allow only moves to adjacent positions rather than any index ahead.
- arrow_right_alt
Maximize score with multiple penalty types for different transitions.