There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0.
You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i and i + 1 for all (0 <= i < n). Return the highest altitude of a point.
The key idea is to track the altitude at each point by accumulating the gains. Since the biker starts at altitude 0, we can compute each subsequent altitude by adding the gain to the previous altitude. The highest altitude is simply the maximum value encountered during this process.
classSolution {
public:int largestAltitude(vector<int>& gain) {
int ans =0, alt =0;
for (int g : gain) {
alt += g;
ans = max(ans, alt);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
funclargestAltitude(gain []int) int {
ans, alt:=0, 0for_, g:=rangegain {
alt+=gifalt > ans {
ans = alt }
}
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
publicintlargestAltitude(int[] gain) {
int ans = 0, alt = 0;
for (int g : gain) {
alt += g;
ans = Math.max(ans, alt);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funlargestAltitude(gain: IntArray): Int {
var ans = 0var alt = 0for (g in gain) {
alt += g
ans = maxOf(ans, alt)
}
return ans
}
}
1
2
3
4
5
6
7
8
classSolution:
deflargestAltitude(self, gain: list[int]) -> int:
ans: int =0 alt: int =0for g in gain:
alt += g
ans = max(ans, alt)
return ans
1
2
3
4
5
6
7
8
9
10
11
impl Solution {
pubfnlargest_altitude(gain: Vec<i32>) -> i32 {
letmut ans =0;
letmut alt =0;
for g in gain {
alt += g;
ans = ans.max(alt);
}
ans
}
}