Skip to content

Instantly share code, notes, and snippets.

@janjackson
Created January 5, 2023 11:58
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 janjackson/0d49c708f1270641e1a772099e1cbc16 to your computer and use it in GitHub Desktop.
Save janjackson/0d49c708f1270641e1a772099e1cbc16 to your computer and use it in GitHub Desktop.
cassidy interview question of the week
#"hey chatGPT..." ;)
def largest_sum(arr, n):
# If the length of the subarray is greater than the length of the array,
# return the original array
if n > len(arr):
return arr
# Initialize variables to store the largest sum and the start and end indices
# of the subarray
max_sum = 0
max_start = 0
max_end = 0
# Iterate over the array to find the subarray with the largest sum
for i in range(len(arr) - n + 1):
# Calculate the sum of the current subarray
current_sum = sum(arr[i:i+n])
# If the current sum is larger than the largest sum, update the max_sum
# and max_start and max_end variables
if current_sum > max_sum:
max_sum = current_sum
max_start = i
max_end = i + n
# Return the subarray with the largest sum
return arr[max_start:max_end]
# Test the function
print(largest_sum([1, 2, 3, 4, 5], 3)) # Output: [3, 4, 5]
print(largest_sum([1, 2, 3, 4, 5], 6)) # Output: [1, 2, 3, 4, 5]
print(largest_sum([1, 2, 3, 4, 5], 2)) # Output: [4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment