Day 2 โ Max Average Subarray & Highest Altitude | Sliding Window + Prefix Sum | LeetCode Challenge


๐๏ธ Date: July 26, 2025
๐ Challenge:
๐งฉ Problem 1: Maximum Average Subarray I โ LeetCode #643 (Easy)
๐งฉ Problem 2: Find the Highest Altitude โ LeetCode #1732 (Easy)
๐ป Topic: Sliding Window, Prefix Sum, Arrays
โ Problem Statement (Summary):
๐น Problem 1: Maximum Average Subarray I
Goal: Find the contiguous subarray of size k
with the maximum average value.
Example:
Input: nums = [1,12,-5,-6,50,3]
, k = 4
โ Output: 12.75000
Explanation: Subarray [12,-5,-6,50]
โ Sum = 51 โ Avg = 12.75
๐ง What I Learned (Problem 1):
Sliding Window is efficient when we need to compute window sums repeatedly.
Reusing previous window's sum: subtract the first element, add the next.
Store the max window sum and divide at the end for result.
๐งช Code (C++):
class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int win_sum = 0, max_sum = 0;
for (int i = 0; i < k; i++) {
win_sum += nums[i];
}
max_sum = win_sum;
for (int i = k; i < nums.size(); i++) {
win_sum += (nums[i] - nums[i - k]);
max_sum = max(win_sum, max_sum);
}
return double(max_sum) / k;
}
};
๐ Time Complexity: O(n)
๐ฆ Space Complexity: O(1)
๐ธ LeetCode Submission Screenshot:
โ Key Takeaways:
Use fixed-size sliding window for k-length subarrays
Keep track of running sum to optimize computation
Divide by k only once at the end
๐น Problem 2: Find the Highest Altitude
Goal: Return the highest point reached based on gain[]
changes in altitude.
Example:
Input: gain = [-5,1,5,0,-7]
โ Output: 1
Explanation: Altitudes = [0, -5, -4, 1, 1, -6]
, max = 1
๐ง What I Learned (Problem 2):
Treat gain array as prefix sum over time.
Start from altitude 0 and keep updating cumulative gain.
Track max altitude as we traverse.
๐งช Code (C++):
class Solution {
public:
int largestAltitude(vector<int>& gain) {
int maxGain = 0;
int netGain = gain[0];
maxGain = max(netGain, maxGain);
for (int i = 1; i < gain.size(); i++) {
netGain += gain[i];
maxGain = max(netGain, maxGain);
}
return maxGain;
}
};
๐ Time Complexity: O(n)
๐ฆ Space Complexity: O(1)
๐ธ LeetCode Submission Screenshot:
โ Key Takeaways:
Start altitude is always 0
Running prefix sum tracks cumulative altitude
Track max at each step to find peak
๐ Progress Tracker:
โ
Day: 2 / 30
๐งฉ Total Problems Solved: 3
๐งญ Focus Today: Sliding Window + Prefix Sum
๐๏ธ Tags:#leetcode
#30DaysChallenge
#slidingwindow
#prefixsum
#cpp
#dsa
#arrays
#maxaverage
#altitude
#codingjourney
Subscribe to my newsletter
Read articles from Tanishi directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
