To 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.
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.
1function highestAltitude(gain) {
2 let maxAltitude = 0;
3 let currentAltitude = 0;
4 for (let i = 0; i < gain.length; i++) {
5 currentAltitude += gain[i];
6 if (currentAltitude > maxAltitude) {
7 maxAltitude = currentAltitude;
8 }
9 }
10 return maxAltitude;
11}
12
13console.log(highestAltitude([-5, 1, 5, 0, -7]));
In JavaScript, the function iterates through the gain array, incrementing currentAltitude at each step and updating maxAltitude as necessary. It's a straightforward approach to find the maximum altitude throughout the journey.