Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find the highest altitude of a point in Python
Suppose there is a biker going on a road trip through n different points at various altitudes. The biker starts from point 0 with altitude 0. Given a sequence called gain with n elements, gain[i] represents the net gain in altitude between points i and i + 1. We need to find the highest altitude reached during the trip.
For example, if gain = [-4, 2, 6, 1, -6], the altitudes at each point would be [0, -4, -2, 4, 5, -1], making the highest altitude 5.
Algorithm
To solve this problem, we follow these steps ?
Initialize
maximum = 0(starting altitude)Initialize
current_altitude = 0-
For each altitude gain in the sequence:
Add the gain to current altitude
Update maximum if current altitude is higher
Return the maximum altitude found
Implementation
def solve(gain):
maximum = 0
current_altitude = 0
for delta in gain:
current_altitude += delta
maximum = max(maximum, current_altitude)
return maximum
# Test with example
gain = [-4, 2, 6, 1, -6]
result = solve(gain)
print(f"Highest altitude: {result}")
# Let's also see the altitude at each point
altitudes = [0]
current = 0
for delta in gain:
current += delta
altitudes.append(current)
print(f"Altitudes at each point: {altitudes}")
Highest altitude: 5 Altitudes at each point: [0, -4, -2, 4, 5, -1]
How It Works
The algorithm maintains a running sum of altitude changes and tracks the maximum altitude encountered. Starting from altitude 0, we add each gain value and check if the new altitude is the highest so far.
Alternative Approach
We can also solve this using Python's built-in functions with a more concise approach ?
def solve_alternative(gain):
altitudes = [0]
current = 0
for delta in gain:
current += delta
altitudes.append(current)
return max(altitudes)
# Test the alternative approach
gain = [-4, 2, 6, 1, -6]
result = solve_alternative(gain)
print(f"Highest altitude: {result}")
Highest altitude: 5
Comparison
| Approach | Space Complexity | Time Complexity | Best For |
|---|---|---|---|
| Running Maximum | O(1) | O(n) | Memory efficiency |
| Store All Altitudes | O(n) | O(n) | When you need all altitudes |
Conclusion
The running maximum approach efficiently tracks the highest altitude in O(1) space complexity. This algorithm is perfect for finding peak values in cumulative sum problems where memory efficiency is important.
