From 9420670c175ef2bc856100b3bb8625dec6a7691e Mon Sep 17 00:00:00 2001 From: Ahmed Gamal Date: Tue, 20 Jun 2023 09:04:57 +0300 Subject: [PATCH] Add solution to day 20 --- ...Radius Subarray Averages (Ahmed Gamal).cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 06- June/20- K Radius Subarray Averages/20- K Radius Subarray Averages (Ahmed Gamal).cpp diff --git a/06- June/20- K Radius Subarray Averages/20- K Radius Subarray Averages (Ahmed Gamal).cpp b/06- June/20- K Radius Subarray Averages/20- K Radius Subarray Averages (Ahmed Gamal).cpp new file mode 100644 index 000000000..1696b0c78 --- /dev/null +++ b/06- June/20- K Radius Subarray Averages/20- K Radius Subarray Averages (Ahmed Gamal).cpp @@ -0,0 +1,26 @@ +// Author: Ahmed Gamal + +// for this problem, we can use prefix sum to calculate the sum of each subarray in O(1) time +// then we can just iterate over the array and calculate the average of each subarray + +class Solution { +public: + vector getAverages(vector& nums, int k) { + // ans[i] = average of subarray [i - k, i + k], if i - k < 0 or i + k >= nums.size() then ans[i] = -1 + // prefix[i] = sum of subarray [0, i - 1] + vector ans(nums.size(), -1); + vector prefix(nums.size() + 1); + + // calculate prefix sum + for(int i = 1; i < prefix.size(); i++) { + prefix[i] += nums[i - 1] + prefix[i - 1]; + } + + // calculate the average of each subarray (from k + 1 to nums.size() - k) + for(int i = k + 1; i + k < prefix.size(); i++) { + ans[i - 1] = (prefix[i + k] - prefix[i - k - 1]) / (k << 1 | 1); + } + + return ans; + } +}; \ No newline at end of file