Created
January 5, 2023 11:58
-
-
Save janjackson/0d49c708f1270641e1a772099e1cbc16 to your computer and use it in GitHub Desktop.
cassidy interview question of the week
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
#"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