Dare2Solve
The problem is to find the highest altitude reached after performing a series of gains and losses starting from an initial altitude of zero. Each element in the input array gain
represents a change in altitude. The goal is to compute the maximum altitude attained after applying all the changes.
To solve this problem, you can iteratively compute the altitude after each change in the gain
array, starting from an altitude of zero. As you compute each new altitude, you track the maximum altitude reached.
Initialization: Start with an initial altitude of 0
. Keep track of the maximum altitude as you iterate through the gain
array.
Iteration: For each value in the gain
array, update the current altitude by adding the gain to the previous altitude.
Tracking Maximum: After updating the altitude, compare it with the current maximum altitude and update the maximum if the new altitude is higher.
Return Result: Once all gains have been processed, the maximum altitude recorded will be the result.
O(n), where n
is the length of the gain
array. This is because we only need to iterate through the array once.
O(1), as we only use a few variables to store the current altitude and the maximum altitude, regardless of the input size.
class Solution {
public:
int largestAltitude(std::vector<int>& gain) {
int sum = 0;
int maxAlt = 0;
for (int i = 0; i < gain.size(); i++) {
sum += gain[i];
maxAlt = std::max(maxAlt, sum);
}
return maxAlt;
}
};
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
sum = 0
max_alt = 0
for g in gain:
sum += g
max_alt = max(max_alt, sum)
return max_alt
class Solution {
public int largestAltitude(int[] gain) {
int sum = 0;
int maxAlt = 0;
for (int i = 0; i < gain.length; i++) {
sum += gain[i];
maxAlt = Math.max(maxAlt, sum);
}
return maxAlt;
}
}
var largestAltitude = function (gain) {
let sum = 0;
let alt = [];
let max;
for (let i = 0; i <= gain.length; i++) {
alt.push(sum);
sum = sum + gain[i];
}
max = alt[0];
for (let j = 0; j < alt.length; j++) {
if (max < alt[j]) {
max = alt[j];
}
}
return max;
}