The Find the Highest Altitude problem requires finding the highest altitude reached during a journey based on the changes in altitude between consecutive points.

Problem

Given an integer array gain, where gain[i] represents the net gain in altitude between points i and i + 1, the journey starts at an altitude of 0.

Return the highest altitude reached during the journey.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

Input
gain = [-5,1,5,0,-7]
Output
1

Example 2

Input
gain = [-4,-3,-2,-1,4,3,2]
Output
0

Solution

This solution uses the Prefix Sum technique. We start with the current altitude as 0 and add each gain value to calculate the altitude at the next point.

After calculating each altitude, we update the maximum altitude reached so far. Since the altitude at each point depends on all previous gains, this running total represents a prefix sum.
class Solution {
    public int largestAltitude(int[] gain) {
        int altitude = 0;
        int maxAltitude = 0;

        for (int i = 0; i < gain.length; i++) {
            altitude += gain[i];
            maxAltitude = Math.max(maxAltitude, altitude);
        }

        return maxAltitude;
    }
}

Complexity

Each element is processed exactly once, so the time complexity is O(n), where n is the length of the array.

The solution uses only a few variables to maintain the current and maximum altitude, so the extra space complexity is O(1).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion