LeetCode 题解工作台
最大交替子序列和
一个下标从 0 开始的数组的 交替和 定义为 偶数 下标处元素之 和 减去 奇数 下标处元素之 和 。 比方说,数组 [4,2,5,3] 的交替和为 (4 + 5) - (2 + 3) = 4 。 给你一个数组 nums ,请你返回 nums 中任意子序列的 最大交替和 (子序列的下标 重新 从 0…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示从前 个元素中选出的子序列,且最后一个元素为奇数下标时的最大交替和,定义 表示从前 个元素中选出的子序列,且最后一个元素为偶数下标时的最大交替和。初始时 $f[0] = g[0] = 0$。答案为 $max(f[n], g[n])$。 我们考虑第 个元素 $nums[i - 1]$:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
一个下标从 0 开始的数组的 交替和 定义为 偶数 下标处元素之 和 减去 奇数 下标处元素之 和 。
- 比方说,数组
[4,2,5,3]的交替和为(4 + 5) - (2 + 3) = 4。
给你一个数组 nums ,请你返回 nums 中任意子序列的 最大交替和 (子序列的下标 重新 从 0 开始编号)。
一个数组的 子序列 是从原数组中删除一些元素后(也可能一个也不删除)剩余元素不改变顺序组成的数组。比方说,[2,7,4] 是 [4,2,3,7,2,1,4] 的一个子序列(加粗元素),但是 [2,4,2] 不是。
示例 1:
输入:nums = [4,2,5,3] 输出:7 解释:最优子序列为 [4,2,5] ,交替和为 (4 + 5) - 2 = 7 。
示例 2:
输入:nums = [5,6,7,8] 输出:8 解释:最优子序列为 [8] ,交替和为 8 。
示例 3:
输入:nums = [6,2,1,2,4,5] 输出:10 解释:最优子序列为 [6,1,5] ,交替和为 (6 + 5) - 1 = 10 。
提示:
1 <= nums.length <= 1051 <= nums[i] <= 105
解题思路
方法一:动态规划
我们定义 表示从前 个元素中选出的子序列,且最后一个元素为奇数下标时的最大交替和,定义 表示从前 个元素中选出的子序列,且最后一个元素为偶数下标时的最大交替和。初始时 。答案为 。
我们考虑第 个元素 :
如果选取该元素且该元素为奇数下标,那么上一个元素必须为偶数下标,且只能从前 个元素中选取,因此 ;如果不选取该元素,那么 。
同理,如果选取该元素且该元素为偶数下标,那么上一个元素必须为奇数下标,且只能从前 个元素中选取,因此 ;如果不选取该元素,那么 。
综上,我们可以得到状态转移方程:
最终答案为 。
我们注意到 和 只与 和 有关,因此我们可以使用两个变量代替数组,将空间复杂度降低到 。
时间复杂度 ,其中 为数组长度。
class Solution:
def maxAlternatingSum(self, nums: List[int]) -> int:
n = len(nums)
f = [0] * (n + 1)
g = [0] * (n + 1)
for i, x in enumerate(nums, 1):
f[i] = max(g[i - 1] - x, f[i - 1])
g[i] = max(f[i - 1] + x, g[i - 1])
return max(f[n], g[n])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for the ability to optimize both time and space complexity in dynamic programming solutions.
- question_mark
Assess the candidate's understanding of alternating sum and how dynamic programming applies.
- question_mark
Check whether the candidate can correctly handle the state transitions between even and odd indexed subsequences.
常见陷阱
外企场景- error
Misunderstanding the alternating sum definition, which may lead to incorrect subsequences.
- error
Failing to optimize space by using unnecessary arrays for each possible subsequence.
- error
Not handling edge cases, such as very small arrays or arrays with only one element.
进阶变体
外企场景- arrow_right_alt
Consider the scenario where the input array contains a single element.
- arrow_right_alt
Explore the impact of large input sizes on performance and how to optimize for such cases.
- arrow_right_alt
Challenge the candidate with an extension that requires finding the subsequence with the maximum alternating sum while also considering additional constraints.