[C++] Clean Code


  • 2
    class Solution {
    public:
        double findMaxAverage(vector<int>& nums, int k) {
            int maxsum = INT_MIN;
            int sum = 0;
            // k = min((size_t)k, nums.size());
            for (int i = 0; i < nums.size(); i++) {
                sum += nums[i];
                if (i >= k) {
                    sum -= nums[i - k];
                }
                if (i >= k - 1) {
                    maxsum = max(maxsum, sum);            
                }
            }
            return (double)maxsum / k;
        }
    };
    

  • 0
    L

    Can this be done using a HashTable, something along the lines of SubArray sum equals k?


  • 0
    M

    @lkjhgfdsa I have tried, but unfortunately, if you want to make the sum of k numbers be the hash function and sort their order according to their sum which act as their index in hash table, then just search the max index, you will find out that the run time is too much.


  • 0
    L

    @mozart1998 Yes, thank you so much. I appreciate your help. I am trying to improve my analysis skills so that when I see some question, I would be able to link it to some question that I have solved before.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.