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
This problem involves finding the highest altitude reached during a bike trip, given an array gain
where gain[i]
represents the net gain in altitude between points i
and i+1
. The biker starts at altitude 0.
Approach:
The most efficient approach leverages the concept of prefix sums (also known as cumulative sums). The altitude at each point can be calculated by accumulating the gains. The highest altitude will be the maximum of these accumulated altitudes.
Algorithm:
Initialization: Start with a variable highestAltitude
set to 0 (the initial altitude). Also, initialize a variable currentAltitude
to 0.
Iteration: Iterate through the gain
array:
gain[i]
to currentAltitude
.highestAltitude
if currentAltitude
is greater.Return: After iterating through the entire gain
array, return highestAltitude
.
Time Complexity Analysis:
The algorithm iterates through the gain
array once. Therefore, the time complexity is O(n), where n is the length of the gain
array.
Space Complexity Analysis:
The algorithm uses a few variables to store the current altitude and the highest altitude. The space used is constant regardless of the input size. Therefore, the space complexity is O(1).
Code Implementation (Python):
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
highest_altitude = 0
current_altitude = 0
for gain_value in gain:
current_altitude += gain_value
highest_altitude = max(highest_altitude, current_altitude)
return highest_altitude
Code Implementation (Java):
class Solution {
public int largestAltitude(int[] gain) {
int highestAltitude = 0;
int currentAltitude = 0;
for (int gainValue : gain) {
currentAltitude += gainValue;
highestAltitude = Math.max(highestAltitude, currentAltitude);
}
return highestAltitude;
}
}
Code Implementation (C++):
class Solution {
public:
int largestAltitude(vector<int>& gain) {
int highestAltitude = 0;
int currentAltitude = 0;
for (int gainValue : gain) {
currentAltitude += gainValue;
highestAltitude = max(highestAltitude, currentAltitude);
}
return highestAltitude;
}
};
The code in other languages (JavaScript, Go, Rust, PHP, C) follows a very similar structure, adapting the syntax to each language's specifics while maintaining the same algorithmic logic. The core idea remains consistent across all implementations.