Maximum sum of a contiguous subarray
January 1, 2024
Problem #
Given a list of integers, find the maximum sum of a contiguous subarray with length 3.
Solution #
Here’s the Python code to find the maximum sum of a contiguous subarray of length 3 in a given list of integers:
def maxSumSubarrayOfSizeThree(nums):
"""
Find the maximum sum of a contiguous subarray of size 3.
Args:
nums (List[int]): A list of integers.
Returns:
int: The maximum sum of a contiguous subarray of size 3.
"""
if len(nums) < 3:
return "List is too short for a subarray of size 3."
max_sum = current_sum = sum(nums[:3])
for i in range(3, len(nums)):
current_sum = current_sum - nums[i - 3] + nums[i]
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage
nums_list = [1, 2, 3, 4, 5]
max_sum = maxSumSubarrayOfSizeThree(nums_list)
print(max_sum)
For the example list [1, 2, 3, 4, 5]
, the function calculates the maximum sum of a contiguous subarray of size 3, which is 12
(from the subarray [3, 4, 5]
).
The function works by first checking if the list is long enough to have a subarray of size 3. It then initializes the maximum sum (max_sum
) with the sum of the first three elements. It iterates through the list, updating the current sum (current_sum
) for each subarray of size 3 by subtracting the element that is no longer in the subarray and adding the new element. After each iteration, it updates max_sum
if a higher sum is found.