-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: k radius subarray averages using sliding window prefix sum
- Loading branch information
1 parent
1863d8b
commit 912fcdb
Showing
2 changed files
with
32 additions
and
0 deletions.
There are no files selected for viewing
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,17 @@ | ||
from typing import List | ||
|
||
|
||
# O(n) time || O(1) space | ||
def get_averages(self, nums: List[int], k: int) -> List[int]: | ||
n = len(nums) | ||
res = [-1] * n | ||
|
||
left, curr_window_sum, diameter = 0, 0, 2 * k + 1 | ||
for right in range(n): | ||
curr_window_sum += nums[right] | ||
if right - left + 1 >= diameter: | ||
res[left + k] = curr_window_sum // diameter | ||
curr_window_sum -= nums[left] | ||
left += 1 | ||
|
||
return res |
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,15 @@ | ||
import unittest | ||
|
||
from arrays.KRadiusSubarrayAverages import get_averages | ||
|
||
|
||
class MyTestCase(unittest.TestCase): | ||
def test_get_averages(self): | ||
self.assertEqual([-1, -1, -1, 5, 4, 4, -1, -1, -1], get_averages(self, [7, 4, 3, 9, 1, 8, 5, 2, 6], 3)) | ||
|
||
def test_get_averages_1(self): | ||
self.assertEqual([100000], get_averages(self, [100000], 0)) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |