Created
January 2, 2023 17:41
-
-
Save les-peters/672608c83a2c703692edbe5a93ecbe25 to your computer and use it in GitHub Desktop.
Max Sub Array
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
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