From 1c30e6f4c8b78bb9774cc9a35c81644fbc044343 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Sun, 5 Nov 2023 00:03:38 -0400 Subject: [PATCH] adding a sliding window problem --- leetcode/p643_max_average_subarray.cpp | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 leetcode/p643_max_average_subarray.cpp diff --git a/leetcode/p643_max_average_subarray.cpp b/leetcode/p643_max_average_subarray.cpp new file mode 100644 index 0000000..344f5a1 --- /dev/null +++ b/leetcode/p643_max_average_subarray.cpp @@ -0,0 +1,28 @@ +// sliding window problem. +// O(n) solution +class Solution { +public: + double findMaxAverage(vector& nums, int k) { + double result = INT_MIN; + double sum = 0.00; + int size = nums.size(); + int low = 0; + int high = 0; + while(high result){ + result = sum; + } + // always make sure there are no more than k elements in this sum. + sum -= nums[low]; + // slide the window + low++; + } + // slide the window + high++; + } + result = result/k; + return result; + } +};