LeetCode 题解工作台

找到最高海拔

有一个自行车手打算进行一场公路骑行,这条路线总共由 n + 1 个不同海拔的点组成。自行车手从海拔为 0 的点 0 开始骑行。 给你一个长度为 n 的整数数组 gain ,其中 gain[i] 是点 i 和点 i + 1 的 净海拔高度差 ( 0 )。请你返回 最高点的海拔 。 示例 1: 输入: …

category

2

题型

code_blocks

8

代码语言

hub

3

相关题

当前训练重点

简单 · 前缀和

bolt

答案摘要

我们假设每个点的海拔为 ,由于 表示第 个点和第 $i + 1$ 个点的海拔差,因此 $gain[i] = h_{i + 1} - h_i$。那么: $$

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

有一个自行车手打算进行一场公路骑行,这条路线总共由 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.length
  • 1 <= n <= 100
  • -100 <= gain[i] <= 100
lightbulb

解题思路

方法一:前缀和(差分数组)

我们假设每个点的海拔为 hih_i,由于 gain[i]gain[i] 表示第 ii 个点和第 i+1i + 1 个点的海拔差,因此 gain[i]=hi+1higain[i] = h_{i + 1} - h_i。那么:

i=0n1gain[i]=h1h0+h2h1++hnhn1=hnh0=hn\sum_{i = 0}^{n-1} gain[i] = h_1 - h_0 + h_2 - h_1 + \cdots + h_n - h_{n - 1} = h_n - h_0 = h_n

即:

hi+1=j=0igain[j]h_{i+1} = \sum_{j = 0}^{i} gain[j]

可以发现,每个点的海拔都可以通过前缀和的方式计算出来。因此,我们只需要遍历一遍数组,求出前缀和的最大值,即为最高点的海拔。

实际上题目中的 gaingain 数组是一个差分数组,对差分数组求前缀和即可得到原海拔数组。然后求出原海拔数组的最大值即可。

时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。其中 nn 为数组 gaingain 的长度。

1
2
3
4
class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        return max(accumulate(gain, initial=0))
speed

复杂度分析

指标
时间O(N)
空间O(1)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

找到最高海拔题解:前缀和 | LeetCode #1732 简单