Skip to content

Instantly share code, notes, and snippets.

@les-peters
Created April 23, 2022 16:53
Show Gist options
  • Save les-peters/98a06a3a11f72099f4781796ae6c4a5e to your computer and use it in GitHub Desktop.
Save les-peters/98a06a3a11f72099f4781796ae6c4a5e to your computer and use it in GitHub Desktop.
Largest Subarray Sum
question = """
Given an unsorted array of integers and a number n, find the subarray of length n that has the largest sum.
Example:
$ largestSubarraySum([3,1,4,1,5,9,2,6], 3)
$ [9, 2, 6]
"""
from functools import reduce
def largestSubarraySum(a, l):
largest_sum = 0
largest_sum_i = 0
for i in range(0, len(a)-2):
t = reduce(lambda x, y: x + y, a[i:i+3])
if t > largest_sum:
largest_sum = t
largest_sum_i = i
return a[largest_sum_i:largest_sum_i+3]
print(largestSubarraySum([3,1,4,1,5,9,2,6], 3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment