Leetcode 1732. Find the Highest Altitude
A cyclist rides a bike on a road that follows a sequence of points with varying altitudes. You are given an array gain where gain[i] is the net gain (or loss) in altitude between point i and point i + 1 for all i (0 ≤ i < gain.length). The initial altitude is 0, and you need to return the highest altitude the cyclist reaches.
gain is empty, the starting altitude (which is 0) is the highest altitude.gain array, updating the current altitude at each step by adding the net gain (or subtracting if it’s a loss).gain array because we only need a single pass through the array.#include <vector>
#include <algorithm> // for max
int largestAltitude(std::vector<int>& gain) {
int current_altitude = 0;
int highest_altitude = 0;
for (int g : gain) {
current_altitude += g;
highest_altitude = std::max(highest_altitude, current_altitude);
}
return highest_altitude;
}
Here’s a brief description of the code:
current_altitude) and initialize highest_altitude to 0.current_altitude by adding the current gain value. Use std::max to update highest_altitude if current_altitude is higher.This solution ensures we efficiently track the highest altitude without needing additional space beyond a few integer variables.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?