Suppose there is a biker who is going on a road trip. There are n different points in his road trip at different altitudes. The biker starts his trip from point 0 with altitude 0. If we have a sequence called gain with n elements, gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). We have to find the highest altitude of a point.
So, if the input is like gain = [-4,2,6,1,-6], then the output will be 5, because the altitudes are [0,-4,-2,4,5,-1], so the maximum is 5.
To solve this, we will follow these steps −
maximum := 0
run_alt := 0
for each delta in gain, do
run_alt := run_alt + delta
maximum := max of maximum and run_alt
Let us see the following implementation to get better understanding −
def solve(gain): maximum = 0 run_alt = 0 for delta in gain: run_alt += delta maximum = max(maximum, run_alt) return maximum gain = [-4,2,6,1,-6] print(solve(gain))