Grokking the Coding Interview: Patterns for Coding Questions
Vote

0% completed

​

Solution: Maximum Sum Subarray of Size K

.....

.....

.....

Like the course? Get enrolled and start learning!
A

Anonymous

· 2 years ago

class Solution:   def findMaxSumSubArray(self,k, arr):     maxSum = 0     l = 0     for i in range(l,len(arr)):       curSum = sum(arr[l:l+k])       maxSum = max(maxSum, curSum)       l += 1     return maxSum
A

Anonymous

· 3 years ago

class Solution: def findMaxSumSubArray(self,k, arr): # TODO: Write your code here maxsum=[] for i in range(0,len(arr)-k+1): maxsum=max(maxsum,arr[i:i+k],key=sum) return sum(maxsum)
A

Anonymous

· 3 years ago

class Solution: def findMaxSumSubArray(self,k, arr): # Check if arra is empty if not arr: return -1 # Pointer to leftmost index of our window l = 0 # Set max_so_far to the sum max_so_far = sum(arr[:k]) curr_sum = max_so_far # Start iterating from size k onwards for r in range(k, len(arr)): # Add element from right into current sum curr_sum += arr[r] # Now check if our window exceeds size k if (r - l) + 1 > k: # Subtrack leftmost element of window curr_sum -= arr[l] # Shift left l += 1 # In either case, update max max_so_far = max(max_so_far, curr_sum) return max_so_far
A

Anonymous

· 5 years ago

I am comparing this problem to what I see on leetcode for 643. Maximum Average Subarray I. When you have to account for negative numbers, this solution in the course does not work. How do we modify our solution to make it work with negative numbers?

Show 6 replies

Reading Progress

0%


Vote for new content