Find the highest altitude

November 17, 2022

array-and-hashmap

Problem URL: Find the highest altitude

We will iterate over the gain array and add the gain to the current altitude. We will update the maximum altitude if the current altitude is greater than the maximum altitude.

class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        maxAltitude = 0
        currentAltitude = 0
        for i in gain:
            currentAltitude += i
            maxAltitude = max(maxAltitude, currentAltitude)
        return maxAltitude

We can also achieve the same thing in one line code-

class Solution:
    def largestAltitude(self, gain: List[int]) -> int:
        return max(0, max(accumulate(gain)))

Time complexity: O(n)
Space complexity: O(1)