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.
1#include <stdio.h>
2
3int highestAltitude(int* gain, int n) {
4 int max_altitude = 0;
5 int current_altitude = 0;
6 for (int i = 0; i < n; i++) {
7 current_altitude += gain[i];
8 if (current_altitude > max_altitude) {
9 max_altitude = current_altitude;
10 }
11 }
12 return max_altitude;
13}
14
15int main() {
16 int gain[] = {-5, 1, 5, 0, -7};
17 int n = sizeof(gain) / sizeof(gain[0]);
18 printf("%d", highestAltitude(gain, n));
19 return 0;
20}
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.