找到最高海拔【LC1732】
There is a biker going on a road trip. The road trip consists of
n + 1
points at different altitudes. The biker starts his trip on point0
with altitude equal0
.You are given an integer array
gain
of lengthn
wheregain[i]
is the net gain in altitude between pointsi
andi + 1
for all (0 <= i < n)
. Return the highest altitude of a point.
有一个自行车手打算进行一场公路骑行,这条路线总共由
n + 1
个不同海拔的点组成。自行车手从海拔为0
的点0
开始骑行。给你一个长度为
n
的整数数组gain
,其中gain[i]
是点i
和点i + 1
的 净海拔高度差(0 <= i < n
)。请你返回 最高点的海拔 。
美好的一天从leetcode开始
-
思路:遍历数组,使用前缀和求每一个点的海拔高度,取最大值返回既可
-
实现
class Solution { public int largestAltitude(int[] gain) { int res = 0; int height = 0; for (int i = 0; i < gain.length; i++){ height += gain[i]; res = Math.max(res,height); } return res; } }
-
复杂度
- 时间复杂度:O(n)O(n)O(n),n为数组长度
- 空间复杂度:O(1)O(1)O(1)