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.
1using System;
2
3public class Program {
4 public static int HighestAltitude(int[] gain) {
5 int maxAltitude = 0;
6 int currentAltitude = 0;
7 foreach (int g in gain) {
8 currentAltitude += g;
9 if (currentAltitude > maxAltitude) {
10 maxAltitude = currentAltitude;
11 }
12 }
13 return maxAltitude;
14 }
15
16 public static void Main() {
17 int[] gain = {-5, 1, 5, 0, -7};
18 Console.WriteLine(HighestAltitude(gain));
19 }
20}
The solution iterates through each gain value to update current altitude and checks against the maximum altitude. This approach ensures using the minimum necessary operations to find the result.