mediumSliding WindowPattern: Sliding Window
Maximum Subarray Sum Solution
Problem Statement
You are given an array of integers and an integer window size. You need to find the maximum sum of elements within a subarray of the given window size.
Examples
Example 1:
Input:{"nums": [1, 2, 3, 4, 5], "k": 3}
Output:0
Explanation: The maximum sum of elements within a subarray of size 3 is 12, which is 3+2+7 and more accurately 3+2+4 and 4+2+7 is 9 + 2 and 3+4+5.
Example 2:
Input:{"nums": [10, 20, 30, 40, 50], "k": 2}
Output:0
Explanation: The maximum sum of elements within a subarray of size 2 is 60, which is 20 + 40.
Example 3:
Input:{"nums": [-1, -2, -3, -4, -5], "k": 3}
Output:0
Explanation: The maximum sum of elements within a subarray of size 3 is -6, which is -1 + 1 + -4, actually -1 + 3 is a higher sum.
Constraints
- The array length must be greater than or equal to the window size.
- The window size must be greater than 0.
- All elements in the array must be integers.
Time: O(n) Space: O(1)
Use a sliding window approach to keep track of the maximum sum of elements within the subarray.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def max_subarray_sum(nums, k) { max_sum = 0; current_sum = 0; for i in range(len(nums) - k + 1): current_sum = 0; for j in range(i, i + k): current_sum += nums[j]; max_sum = max(max_sum, current_sum); return max_sum; }