描述
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 point 0 with altitude equal 0.
You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point.
Example 1:
Input: gain = [-5,1,5,0,-7]
Output: 1
Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.
Example 2:
Input: gain = [-4,-3,-2,-1,4,3,2]
Output: 0
Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0.
Note:
n == gain.length
1 <= n <= 100
-100 <= gain[i] <= 100
解析
根据题意,gain 中的每个值就是比前一个点高出来的高度增益值(正值表示增加,负值表示降低),起始点的高度为 0 ,之后的每个点的高度就是前一个点的高度与高度增益值的和,最后找到最高的高度即可。
解答
class Solution(object):
def largestAltitude(self, gain):
"""
:type gain: List[int]
:rtype: int
"""
r = 0
gain = [0]+gain
for i in range(1, len(gain)):
gain[i] = gain[i-1] + gain[i]
r = max(r, gain[i])
return r
运行结果
Runtime: 20 ms, faster than 79.20% of Python online submissions for Find the Highest Altitude.
Memory Usage: 13.3 MB, less than 72.94% of Python online submissions for Find the Highest Altitude.
原题链接:https://leetcode.com/problems/find-the-highest-altitude/