FIND THE HIGHEST ALTITUDE PROGRAM IN JAVA

By | March 27, 2024

Example 1:Input: gain = [-5,1,5,0,-7]
Output: 1
Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1.

public class HighestAltitude {
    public static int highestAltitude(int[] gain) {
        int maxAltitude = 0;
        int currentAltitude = 0;
        
        for (int i = 0; i < gain.length; i++) {
            currentAltitude += gain[i];
            maxAltitude = Math.max(maxAltitude, currentAltitude);
        }
        
        return maxAltitude;
    }

    public static void main(String[] args) {
        int[] gain = {-5, 1, 5, 0, -7};
        int result = highestAltitude(gain);
        System.out.println(result);
    }
}

To find the highest altitude of a point during a road trip, we can iterate through the gain array and calculate the cumulative altitude at each point. Then, we track the maximum altitude reached during the trip. Here’s the Java program implementing this approach:

Leave a Reply

Your email address will not be published. Required fields are marked *