LeetCode 1732: Find the Highest Altitude
Problem Description
Explanation
To find the highest altitude reached during the road trip, we can iterate through the gain
array and keep track of the current altitude. We start with altitude 0 and update it based on the net gain at each point. Finally, we return the maximum altitude reached.
- Initialize a variable
altitude
to 0. - Iterate through the
gain
array. - Update the
altitude
by adding the gain at each point. - Update the highest altitude reached if the current altitude is greater than the previous highest altitude.
- Return the highest altitude reached.
Time complexity: O(n)
Space complexity: O(1)
Solutions
class Solution {
public int largestAltitude(int[] gain) {
int maxAltitude = 0;
int altitude = 0;
for (int i = 0; i < gain.length; i++) {
altitude += gain[i];
maxAltitude = Math.max(maxAltitude, altitude);
}
return maxAltitude;
}
}
Loading editor...