clueless coding // TODO: be smarter

LeetCode Maximum Average Subarray I: CPP Solution



TL;DR Code Solution


double findMaxAverage(vector<int>& nums, int k) {
    double total = 0;
    double elements = 0;
    double avg = INT_MIN;
    for (int i = 0; i < nums.size(); i++) {
        total += nums[i];
        elements++;
        if (elements > k) {
            elements--;
            total -= nums[i - k];
        }
        if (elements == k)
        avg = max(avg, total / elements);
    }

    return avg;
}