1. Brute Force — Recomputing Each Window
Intuition
Iterate over every possible starting index i and calculate the sum of the k elements starting at i using an inner loop.
Algorithm
- Initialize
maxSum = -infinity. - Loop
ifrom0tonums.length - k: -
currentSum = 0. - Loop
jfromitoi + k - 1: -
currentSum += nums[j]. -
maxSum = max(maxSum, currentSum). - Return
maxSum / kas a double.
Recompute Each Window Sum (O(N*K) Time)
2 of 2 questions left todayCompute the sum of elements from index 0 to 3 manually
Compute the sum of elements from index 0 to 3 manually.
#include <algorithm>#include <climits>#include <iomanip>#include <iostream>#include <vector>using namespace std; // Brute Force: Recompute sum for every window of size kdouble findMaxAverage(vector<int>& nums, int k) { int n = nums.size(); long long maxSum = LLONG_MIN; for (int i = 0; i <= n - k; i++) { long long currentSum = 0; for (int j = i; j < i + k; j++) { currentSum += nums[j]; } maxSum = max(maxSum, currentSum); } return (double)maxSum / k;} int main() { vector<int> nums = {1, 12, -5, -6, 50, 3}; int k = 4; cout << fixed << setprecision(5); cout << "Output: " << findMaxAverage(nums, k) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Time complexity for Approach 1: Brute Force — Recomputing Each Window. - Space complexity:
O(1)— Space complexity for Approach 1: Brute Force — Recomputing Each Window.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.