Skip to content

Latest commit

 

History

History
20 lines (20 loc) · 677 Bytes

643. Maximum Average Subarray I.md

File metadata and controls

20 lines (20 loc) · 677 Bytes

思路

用一个sum记录当前窗口的和,向右移动窗口找出最大的sum
注意:亲测if(max_sum < sum) max_sum = sum;max_sum = max(max_sum, sum)慢一些

C++

class Solution {
public:
    double findMaxAverage(vector<int>& nums, int k) {
        double sum = 0, max_sum;
        for(int i = 0; i < k; i++) sum += nums[i];
        max_sum = sum;
        for(int i = k; i < nums.size(); i++){
            sum = sum - nums[i - k] + nums[i];
            max_sum = max(sum, max_sum);
        }
        return max_sum / double(k);
    }
};