Facebook Pixel

1732. Find the Highest Altitude

Problem Description

You have a biker traveling on a road trip through n + 1 points at different altitudes. The biker starts at point 0 with an altitude of 0.

You're given an array gain of length n, where gain[i] represents the net altitude change between point i and point i + 1. For example, if gain[0] = 5, it means the altitude increases by 5 units when going from point 0 to point 1.

Your task is to find the highest altitude reached during the entire trip.

To understand this better, let's trace through an example. If gain = [-5, 1, 5, 0, -7]:

  • Start at point 0: altitude = 0
  • Point 1: altitude = 0 + (-5) = -5
  • Point 2: altitude = -5 + 1 = -4
  • Point 3: altitude = -4 + 5 = 1
  • Point 4: altitude = 1 + 0 = 1
  • Point 5: altitude = 1 + (-7) = -6

The altitudes at each point are: [0, -5, -4, 1, 1, -6], so the highest altitude is 1.

The solution uses Python's accumulate function to calculate the running sum (prefix sum) of the gain array, starting from an initial altitude of 0. This gives us all the altitudes at each point. Then max() finds the highest value among all these altitudes.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is recognizing that we need to track the altitude at every point along the journey, not just the final altitude. Since we start at altitude 0 and each element in gain tells us how much the altitude changes between consecutive points, we can calculate the actual altitude at any point by summing up all the gains from the start to that point.

Think of it like tracking your bank balance. If you start with $0 and have a series of transactions (deposits and withdrawals), your balance at any point is the sum of all transactions up to that point. Similarly, the altitude at any point is the sum of all altitude gains from the starting point.

This naturally leads us to the concept of prefix sums (or cumulative sums). The altitude at point i is simply:

  • Altitude at point 0 = 0 (given)
  • Altitude at point 1 = 0 + gain[0]
  • Altitude at point 2 = 0 + gain[0] + gain[1]
  • Altitude at point i = sum of gain[0] through gain[i-1]

Once we realize we need all these cumulative sums, finding the maximum altitude becomes straightforward - we just need to find the largest value among all these prefix sums. Python's accumulate function does exactly this: it generates all prefix sums starting from an initial value (0 in our case), and then we simply apply max() to find the highest altitude reached during the trip.

Learn more about Prefix Sum patterns.

Solution Approach

The solution leverages the concept of prefix sums, which is fundamentally related to difference arrays. The gain array provided in the problem is actually a difference array - it stores the differences between consecutive altitudes.

Let's denote the altitude at point i as h_i. Since gain[i] represents the altitude difference between point i and point i + 1, we have:

  • gain[i] = h_{i+1} - h_i

If we sum up all the gains from point 0 to point n-1, we get:

gain[0] + gain[1] + ... + gain[n-1] 
= (h_1 - h_0) + (h_2 - h_1) + ... + (h_n - h_{n-1})
= h_n - h_0
= h_n  (since h_0 = 0)

This telescoping sum shows that the altitude at any point i+1 can be calculated as:

h_{i+1} = sum of gain[0] through gain[i]

The implementation uses Python's accumulate function from the itertools module to efficiently compute these prefix sums:

  1. accumulate(gain, initial=0): This generates an iterator that produces cumulative sums starting from the initial value of 0. It yields:

    • First value: 0 (the starting altitude)
    • Second value: 0 + gain[0] (altitude at point 1)
    • Third value: 0 + gain[0] + gain[1] (altitude at point 2)
    • And so on...
  2. max(...): Once we have all the altitudes at each point, we simply find the maximum value among them.

This approach is optimal with O(n) time complexity since we traverse the array once, and O(1) extra space complexity as accumulate returns an iterator that computes values on-the-fly rather than storing all values at once.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through a small example with gain = [-4, 3, 2].

Step 1: Understanding the input

  • We have 3 gain values, meaning we'll visit 4 points (0, 1, 2, 3)
  • Starting altitude at point 0 is 0

Step 2: Calculate altitudes using accumulate The accumulate(gain, initial=0) function will compute:

  • Point 0: altitude = 0 (initial value)
  • Point 1: altitude = 0 + (-4) = -4
  • Point 2: altitude = -4 + 3 = -1
  • Point 3: altitude = -1 + 2 = 1

Step 3: Find the maximum altitude From the sequence [0, -4, -1, 1], the maximum value is 1.

Let's trace through how accumulate works internally:

  1. Start with initial value: 0
  2. Add first gain: 0 + (-4) = -4
  3. Add second gain: -4 + 3 = -1
  4. Add third gain: -1 + 2 = 1

The function generates these values as an iterator: (0, -4, -1, 1)

Step 4: Apply max() max(accumulate([-4, 3, 2], initial=0)) returns 1

This matches our expected result - the biker reaches a maximum altitude of 1 meter during the trip, which occurs at the final point.

Solution Implementation

1class Solution:
2    def largestAltitude(self, gain: List[int]) -> int:
3        """
4        Find the highest altitude reached during a trip.
5      
6        Args:
7            gain: List of altitude gains between consecutive points
8      
9        Returns:
10            The maximum altitude reached during the trip
11        """
12        from itertools import accumulate
13      
14        # Calculate cumulative sum of gains starting from altitude 0
15        # accumulate() generates running totals: initial altitude (0) + cumulative gains
16        # Example: gain = [−5, 1, 5, 0, −7] → altitudes = [0, −5, −4, 1, 1, −6]
17        altitudes = accumulate(gain, initial=0)
18      
19        # Return the maximum altitude from all points in the journey
20        return max(altitudes)
21
1class Solution {
2    /**
3     * Finds the highest altitude reached during a trip.
4     * Starting from altitude 0, each element in gain represents the altitude change.
5     * 
6     * @param gain Array where gain[i] is the net altitude change between points i and i+1
7     * @return The highest altitude reached during the trip
8     */
9    public int largestAltitude(int[] gain) {
10        // Track the maximum altitude reached
11        int maxAltitude = 0;
12      
13        // Track the current altitude as we traverse
14        int currentAltitude = 0;
15      
16        // Iterate through each altitude change
17        for (int altitudeChange : gain) {
18            // Update current altitude by adding the change
19            currentAltitude += altitudeChange;
20          
21            // Update maximum altitude if current is higher
22            maxAltitude = Math.max(maxAltitude, currentAltitude);
23        }
24      
25        return maxAltitude;
26    }
27}
28
1class Solution {
2public:
3    int largestAltitude(vector<int>& gain) {
4        // Initialize the maximum altitude and current altitude
5        int maxAltitude = 0;  // The highest altitude reached (starts at 0)
6        int currentAltitude = 0;  // Current altitude at each point
7      
8        // Iterate through each altitude gain value
9        for (int altitudeGain : gain) {
10            // Update current altitude by adding the gain
11            currentAltitude += altitudeGain;
12          
13            // Update maximum altitude if current altitude is higher
14            maxAltitude = max(maxAltitude, currentAltitude);
15        }
16      
17        // Return the highest altitude reached
18        return maxAltitude;
19    }
20};
21
1/**
2 * Finds the highest altitude reached during a trip
3 * @param gain - Array of altitude gains between consecutive points
4 * @returns The maximum altitude reached during the trip
5 */
6function largestAltitude(gain: number[]): number {
7    // Track the maximum altitude reached
8    let maxAltitude: number = 0;
9  
10    // Track the current altitude (starting at 0)
11    let currentAltitude: number = 0;
12  
13    // Iterate through each altitude gain
14    for (const altitudeGain of gain) {
15        // Update current altitude by adding the gain
16        currentAltitude += altitudeGain;
17      
18        // Update maximum altitude if current altitude is higher
19        maxAltitude = Math.max(maxAltitude, currentAltitude);
20    }
21  
22    return maxAltitude;
23}
24

Time and Space Complexity

The time complexity is O(n), where n is the length of the array gain. The accumulate function iterates through all elements in the array once to compute the cumulative sum, and the max function iterates through the accumulated values once to find the maximum value.

The space complexity is O(n), not O(1) as stated in the reference answer. This is because accumulate returns an iterator that, when consumed by max, creates an intermediate sequence of n+1 values (including the initial value 0). While accumulate itself is a generator and doesn't store all values at once, the max function needs to iterate through all accumulated values, effectively requiring space proportional to the input size.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Forgetting the Starting Altitude of 0

The Pitfall: A common mistake is to only consider the altitudes after applying the gains, forgetting that the biker starts at altitude 0. If you only compute the prefix sums of the gain array without including the initial altitude, you might miss cases where 0 is actually the maximum altitude.

Example of the mistake:

def largestAltitude(self, gain: List[int]) -> int:
    # WRONG: Only considers altitudes after gains
    current_altitude = 0
    max_altitude = float('-inf')  # Missing initial altitude
  
    for g in gain:
        current_altitude += g
        max_altitude = max(max_altitude, current_altitude)
  
    return max_altitude

Why it fails: Consider gain = [-5, -3, -2]. The altitudes are [0, -5, -8, -10]. The maximum is 0 (starting altitude), but the wrong approach would return -5.

The Solution: Always initialize the maximum altitude to 0 or ensure your tracking includes the starting point:

def largestAltitude(self, gain: List[int]) -> int:
    current_altitude = 0
    max_altitude = 0  # Start with initial altitude
  
    for g in gain:
        current_altitude += g
        max_altitude = max(max_altitude, current_altitude)
  
    return max_altitude

2. Misunderstanding the accumulate Function's initial Parameter

The Pitfall: When using accumulate, forgetting to set initial=0 or misunderstanding what it does. Without the initial parameter, accumulate would start from the first element of the array, not from altitude 0.

Example of the mistake:

def largestAltitude(self, gain: List[int]) -> int:
    from itertools import accumulate
    # WRONG: Missing initial=0
    return max(accumulate(gain))

Why it fails: For gain = [-5, 1, 5], accumulate(gain) produces [-5, -4, 1], missing the starting altitude of 0. The correct answer should be 1, but if 0 was the maximum (like with gain = [-5, -3, -2]), this would return -2 instead of 0.

The Solution: Always include initial=0 when using accumulate for this problem to ensure the starting altitude is included in the calculations.

def largestAltitude(self, gain: List[int]) -> int:
    from itertools import accumulate
    return max(accumulate(gain, initial=0))
Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

In a binary min heap, the maximum element can be found in:


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More