Leetcode 1732. Find the Highest Altitude
Given an array of integers gain where gain[i] is the net gain in altitude between the (i-1)-th and the i-th points on a trip, return the highest altitude of a point.
gain?gain positive, negative, or both?Here is a Java solution to the problem.
public class HighestAltitude {
public int largestAltitude(int[] gain) {
int currentAltitude = 0;
int highestAltitude = 0;
for (int i = 0; i < gain.length; i++) {
currentAltitude += gain[i];
if (currentAltitude > highestAltitude) {
highestAltitude = currentAltitude;
}
}
return highestAltitude;
}
public static void main(String[] args) {
HighestAltitude solver = new HighestAltitude();
int[] gain1 = {-5, 1, 5, 0, -7};
System.out.println(solver.largestAltitude(gain1)); // Output: 1
int[] gain2 = {-4, -3, -2, -1, 4, 3, 2};
System.out.println(solver.largestAltitude(gain2)); // Output: 0
}
}
currentAltitude set to 0, which is the starting altitude.highestAltitude is also initially set to 0.gain array:
currentAltitude by adding the current gain to it.currentAltitude exceeds highestAltitude, update highestAltitude to the current value of currentAltitude.currentAltitude and highestAltitude.This approach ensures an efficient solution to the problem while keeping the implementation straightforward.
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?