Taro Logo

Find the Highest Altitude

#34 Most AskedEasy
0 views
Topics:
Arrays

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.

Constraints:

  • n == gain.length
  • 1 <= n <= 100
  • -100 <= gain[i] <= 100

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the length range of the `gain` array, and can the array be empty?
  2. Can the net altitude gains in the array be negative numbers, zero, or only positive integers?
  3. Since the trip starts at an altitude of zero, should the starting altitude of zero be considered as a possible highest altitude if all gains are negative?
  4. What data type are the elements in the `gain` array, and do we need to worry about potential integer overflow during the summation?
  5. If the array is empty, should the function default to returning an altitude of zero?

Brute Force Solution

Approach

Imagine you are tracking a journey made of several individual ups and downs, and you want to know the highest point reached above your starting ground. The brute force approach simulates the journey step by step from the very beginning, calculating your exact elevation at every single stopping point along the way.

Here's how the algorithm would work step-by-step:

  1. Begin your journey at the starting point, where your altitude is zero.
  2. Look at the first change in elevation and calculate your new altitude by adding or subtracting that change from your current position.
  3. Compare this new altitude against a running record of the highest altitude you have reached so far, and update the record if this new height is greater.
  4. Move on to the next change in elevation and repeat the exact same process of calculating the updated altitude and checking it against your record.
  5. Continue this process for every single change in elevation until you reach the very end of the journey.
  6. Once you have checked every single stopping point, look at your final saved record to find the highest altitude you touched.

Code Implementation

def largest_altitude(gain):
    # Initialize starting altitude and highest record to zero for the base ground level
    current_altitude = 0
    highest_altitude = 0
    
    # Iterate through each elevation change to calculate the sequential altitude points
    for elevation_change in gain:
        current_altitude += elevation_change
        
        # Update the max altitude record if the newly reached height surpasses previous peaks
        if current_altitude > highest_altitude:
            highest_altitude = current_altitude
            
    return highest_altitude

Big(O) Analysis

Time Complexity
O(n) – To find the highest altitude, we iterate through the array of elevation changes of size n exactly once to calculate the running sum at each step. For each of the n elements, we perform a constant time addition and a comparison to update our maximum altitude record. This means the total operations scale directly with the number of input elements as n grows. Therefore, the linear sequence of steps results in a time complexity of O(n).
Space Complexity
O(1) – The algorithm only allocates a few primitive variables to track the current altitude and the running maximum altitude during the journey. No additional data structures whose size scales with the input size N are created. Therefore, the extra auxiliary memory consumed remains constant regardless of how many elevation changes are processed. Simplifying this to Big O notation yields O(1) space complexity.

Optimal Solution

Approach

To find the highest altitude reached during a trip, we can imagine ourselves walking along a path and keeping a running tally of our elevation. By tracking our height at every single step of the journey, we can easily identify the peak height we ever touched.

Here's how the algorithm would work step-by-step:

  1. Begin your journey at the starting point, where your current height is zero and your record for the highest height seen so far is also zero.
  2. Take the first stretch of the trip and calculate your new height by adding or subtracting the change in elevation from your current height.
  3. Compare this new height to your current highest height record. If the new height is greater, update your record to this new value.
  4. Continue moving forward through the rest of the trip one stretch at a time, constantly updating your current height and checking it against your record.
  5. Once you reach the very end of the journey, the highest height record you have kept along the way will be your final answer.

Code Implementation

def largest_altitude(gain_elevations):

    current_altitude = 0
    highest_altitude = 0

    # Track altitude changes to ensure we find the absolute peak of the journey.
    for elevation_change in gain_elevations:

        current_altitude += elevation_change

        # Update the record immediately if a new higher peak is reached.
        if current_altitude > highest_altitude:
            highest_altitude = current_altitude

    # Return the maximum height recorded throughout the entire trip.
    return highest_altitude

Big(O) Analysis

Time Complexity
O(n) – To find the highest altitude, we iterate through the gain array of size n exactly once, performing constant time addition and comparison operations at each step. There are no nested loops or recursive calls, meaning the cost is driven entirely by the single pass through the input elements. This results in approximately n operations, which simplifies linearly to O(n).
Space Complexity
O(1) – The algorithm only uses a few primitive variables to track the current height and the highest height seen so far, without allocating any extra data structures that scale with the input. As the input array size N grows, the amount of additional memory remains constant. Therefore, the auxiliary space complexity is strictly constant because we only perform in-place tracking of our elevation at each step.

Edge Cases

Empty gain array
How to Handle:
Return zero immediately since the trip never leaves the starting altitude of zero.
Gain array with a single element
How to Handle:
Compare zero with the single gain value and return the maximum of the two.
All negative altitude gains
How to Handle:
Keep the maximum altitude anchored at zero since the trip starts there and only descends.
All positive altitude gains
How to Handle:
Accumulate the sum continuously and return the final total sum as the highest altitude.
Mix of alternating positive and negative gains
How to Handle:
Maintain a running sum at each step and track the peak value reached throughout the iteration.
Extremely large input array scaling
How to Handle:
Iterate through the array in linear time using a single pass with constant extra space.
Integer overflow from massive cumulative gains
How to Handle:
Ensure standard 32-bit or 64-bit integer types are used to safely accumulate the running altitude sum.
0/37 completed