Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created January 2, 2023 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save les-peters/672608c83a2c703692edbe5a93ecbe25 to your computer and use it in GitHub Desktop.
Save les-peters/672608c83a2c703692edbe5a93ecbe25 to your computer and use it in GitHub Desktop.
Max Sub Array
question = """
Given an array of integers arr and an integer n, return a
subarray of arr of length n where the sum is the largest.
Make sure you maintain the order of the original array, and
if n is greater than arr.length, you can choose what you
want to return.
Example:
> maxSubarray([-4,2,-5,1,2,3,6,-5,1], 4)
> [1,2,3,6]
> maxSubarray([1,2,0,5], 2)
> [0,5]
"""
def addTwo(a,b):
return a + b
from functools import reduce
def maxSubarray(arr, n):
maxArrSum = 0
for i in range(0, 1+len(arr)-n):
possibleMaxSubArr = reduce(addTwo, arr[i:i+n])
if possibleMaxSubArr > maxArrSum:
maxArrSum = possibleMaxSubArr
subArr = arr[i:i+n]
return subArr
print(maxSubarray([-4,2,-5,1,2,3,6,-5,1], 4))
print(maxSubarray([1,2,0,5], 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment