Here is my solution to the problem.
from typing import List
def subarray_sum_fixed(nums: List[int], k: int) → int:
ans = 0
for i in range(len(nums)-k):
ans = max(ans, sum(nums[i:i+k]) )
return ans
If I’m not mistaken, that’s O(kn)
solution, which, still in theory is O(n)
, but in practice it is slower than original solution because you are unnecessarily running another for
-loop on each iteration (the 2nd for
being “masked” by sum()
call)
max_sum = 0
for r in range(k, len(nums)):
max_sum = max(max_sum, sum(nums[r-k:r]))
return max_sum
It would be nice to handle edge case scenarios.
example if nums= [10,20,0, 9] and k = 10