LeetCode 题解工作台
变长子数组求和
给你一个长度为 n 的整数数组 nums 。对于 每个 下标 i ( 0 ),定义对应的子数组 nums[start ... i] ( start = max(0, i - nums[i]) )。 返回为数组中每个下标定义的子数组中所有元素的总和。 子数组 是数组中的一个连续、 非空 的元素序列。 …
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
class Solution: def subarraySum(self, nums: List[int]) -> int:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
给你一个长度为 n 的整数数组 nums 。对于 每个 下标 i(0 <= i < n),定义对应的子数组 nums[start ... i](start = max(0, i - nums[i]))。
返回为数组中每个下标定义的子数组中所有元素的总和。
子数组 是数组中的一个连续、非空 的元素序列。
示例 1:
输入:nums = [2,3,1]
输出:11
解释:
| 下标 i | 子数组 | 和 |
|---|---|---|
| 0 | nums[0] = [2] |
2 |
| 1 | nums[0 ... 1] = [2, 3] |
5 |
| 2 | nums[1 ... 2] = [3, 1] |
4 |
| 总和 | 11 |
总和为 11 。因此,输出 11 。
示例 2:
输入:nums = [3,1,1,2]
输出:13
解释:
| 下标 i | 子数组 | 和 |
|---|---|---|
| 0 | nums[0] = [3] |
3 |
| 1 | nums[0 ... 1] = [3, 1] |
4 |
| 2 | nums[1 ... 2] = [1, 1] |
2 |
| 3 | nums[1 ... 3] = [1, 1, 2] |
4 |
| 总和 | 13 |
总和为 13 。因此,输出为 13 。
提示:
1 <= n == nums.length <= 1001 <= nums[i] <= 1000
解题思路
方法一
class Solution:
def subarraySum(self, nums: List[int]) -> int:
s = list(accumulate(nums, initial=0))
return sum(s[i + 1] - s[max(0, i - x)] for i, x in enumerate(nums))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of prefix sums.
- question_mark
Candidate chooses an appropriate approach based on problem constraints.
- question_mark
Candidate avoids unnecessary recalculations in the solution.
常见陷阱
外企场景- error
Forgetting to calculate the subarray's starting index properly.
- error
Not considering the optimization potential with prefix sums.
- error
Using inefficient algorithms for larger arrays without considering the constraints.
进阶变体
外企场景- arrow_right_alt
Given larger arrays, how can we optimize the brute force approach further?
- arrow_right_alt
What would happen if the array elements were negative? How would this affect the subarray calculations?
- arrow_right_alt
Can the solution be adjusted to return a different value, such as the maximum or minimum sum of the subarrays?