- cant sort it since the subarray needs to be contiguous
- having a fixed size sliding window of size k would allow us to traverse and calculate averages for elements in a contiguous subarray
π€What Did I Struggle With?
~
π‘ Explanation of Solution
same as initial thoughts ^
β Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(1)
π» Implementation of Solution
class Solution {public: double findMaxAverage(vector<int>& nums, int k) { int window_sum = 0; // Compute the sum of the first window for (int i = 0; i < k; ++i) { window_sum += nums[i]; } // Initialize max average with the first window's average double maxAverage = static_cast<double>(window_sum) / k; // Slide the window across the array for (int i = k; i < nums.size(); ++i) { window_sum += nums[i] - nums[i - k]; // Update the window sum maxAverage = max(maxAverage, static_cast<double>(window_sum) / k); // Update max average } return maxAverage; }};