Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Pseudocode:
- # sliding window - need the full object to slide over and the size of the window
- # handle the edge case where the window is bigger than the array
- # calculate the initial window and set the best-found-value to it
- # create a pointer to the start of the window
- # loop through valid values for the end of the window
- # calculate window value
- # update best answer found so far
- # increment start of window
- # return the best answer you found
- Mistakes I've made:
- - I forgot to increment the 'start' index variable.
- - I initialized l to k-1 instead of 0. I guess I got it confused with the r pointer.
- """
- def max_subarray(arr, k):
- if k > len(arr):
- return -1
- max_sum = window_sum = sum(arr[:k])
- l = 0
- for r in range(k, len(arr)):
- window_sum = window_sum - arr[l] + arr[r]
- max_sum = max(window_sum, max_sum)
- l += 1
- return max_sum
- arr = [2, 3, 4, 1, 5]
- print(max_subarray(arr, 3)) # Output: 10, which is the sum of [4, 1, 5]
Advertisement
Add Comment
Please, Sign In to add comment