LeetCode 题解工作台
找到最高海拔
有一个自行车手打算进行一场公路骑行,这条路线总共由 n + 1 个不同海拔的点组成。自行车手从海拔为 0 的点 0 开始骑行。 给你一个长度为 n 的整数数组 gain ,其中 gain[i] 是点 i 和点 i + 1 的 净海拔高度差 ( 0 )。请你返回 最高点的海拔 。 示例 1: 输入: …
2
题型
8
代码语言
3
相关题
当前训练重点
简单 · 前缀和
答案摘要
我们假设每个点的海拔为 ,由于 表示第 个点和第 $i + 1$ 个点的海拔差,因此 $gain[i] = h_{i + 1} - h_i$。那么: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
有一个自行车手打算进行一场公路骑行,这条路线总共由 n + 1 个不同海拔的点组成。自行车手从海拔为 0 的点 0 开始骑行。
给你一个长度为 n 的整数数组 gain ,其中 gain[i] 是点 i 和点 i + 1 的 净海拔高度差(0 <= i < n)。请你返回 最高点的海拔 。
示例 1:
输入:gain = [-5,1,5,0,-7] 输出:1 解释:海拔高度依次为 [0,-5,-4,1,1,-6] 。最高海拔为 1 。
示例 2:
输入:gain = [-4,-3,-2,-1,4,3,2] 输出:0 解释:海拔高度依次为 [0,-4,-7,-9,-10,-6,-3,-1] 。最高海拔为 0 。
提示:
n == gain.length1 <= n <= 100-100 <= gain[i] <= 100
解题思路
方法一:前缀和(差分数组)
我们假设每个点的海拔为 ,由于 表示第 个点和第 个点的海拔差,因此 。那么:
即:
可以发现,每个点的海拔都可以通过前缀和的方式计算出来。因此,我们只需要遍历一遍数组,求出前缀和的最大值,即为最高点的海拔。
实际上题目中的 数组是一个差分数组,对差分数组求前缀和即可得到原海拔数组。然后求出原海拔数组的最大值即可。
时间复杂度 ,空间复杂度 。其中 为数组 的长度。
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
return max(accumulate(gain, initial=0))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Look for the candidate's ability to apply prefix sum in a simple problem setting.
- question_mark
Assess whether the candidate can explain the efficiency of the O(N) time complexity and O(1) space complexity.
- question_mark
Gauge how well the candidate can identify and optimize unnecessary space usage.
常见陷阱
外企场景- error
Overcomplicating the problem by trying to store the altitudes at every point instead of just tracking the highest altitude.
- error
Misunderstanding the prefix sum concept and attempting a more complex solution like nested loops.
- error
Failing to recognize that only a few variables are needed to track the current and maximum altitude, leading to unnecessary space usage.
进阶变体
外企场景- arrow_right_alt
Extend the problem to handle negative altitude changes more effectively by considering additional edge cases.
- arrow_right_alt
Consider situations where the biker stays at the starting altitude or only increases or decreases in a simple pattern.
- arrow_right_alt
Explore the problem with varying input sizes to assess performance with maximum constraints.