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.length1 <= n <= 100-100 <= gain[i] <= 100To solve the problem, calculate the altitude at each point by starting from altitude 0 and adding up the values from the 'gain' array. This involves iterating through the array and keeping track of the current altitude. At each step, update and compare against the maximum altitude to find the highest point reached during the entire trip.
The function highestAltitude initializes the altitude to 0. It then iterates through the array 'gain', updating the current altitude by adding each 'gain[i]' and simultaneously checking if this new altitude is the highest so far. The highest recorded altitude is returned.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the gain array, as we iterate through the gain array once.
Space Complexity: O(1), as no extra space proportional to input size is used.
Find the Highest Altitude | Leetcode daily challenge | Leetcode Easy | Prefix Sum • BinaryMagic • 2,194 views views
Watch 9 more video solutions →Practice Find the Highest Altitude with our built-in code editor and test cases.
Practice on FleetCode