forked from 7oSkaaa/LeetCode_DailyChallenge_2023
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ffe8d42
commit 9420670
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
26 changes: 26 additions & 0 deletions
26
06- June/20- K Radius Subarray Averages/20- K Radius Subarray Averages (Ahmed Gamal).cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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<int> getAverages(vector<int>& 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<int> ans(nums.size(), -1); | ||
vector<long long> 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; | ||
} | ||
}; |