To solve the problem of finding the maximum sum of a subarray of length k using the sliding window technique, follow these steps:
Approach
The sliding window technique efficiently computes the maximum sum by avoiding redundant calculations:
- Initial Window: Calculate the sum of the first k elements (initial window).
- Slide the Window: For each subsequent position, adjust the sum by subtracting the element that exits the window (leftmost element of the previous window) and adding the new element that enters the window (rightmost element of the current window).
- Track Maximum: Keep updating the maximum sum encountered during the sliding process.
Solution Code
def max_subarray_sum_k(arr, k):
n = len(arr)
if n < k:
return 0 # Handle invalid input (array shorter than k)
# Calculate sum of first k elements
current_sum = sum(arr[:k])
max_sum = current_sum
# Slide the window across the array
for i in range(k, n):
current_sum += arr[i] - arr[i - k]
if current_sum > max_sum:
max_sum = current_sum
return max_sum
Explanation
- Initial Window: The sum of the first k elements is computed once (O(k) time).
- Sliding: For each element from index k to the end of the array, we adjust the sum in O(1) time (subtract the left element, add the right element). This results in O(n - k) operations.
- Total Complexity: O(n) time (since O(k) + O(n -k) = O(n)) and O(1) space (no extra data structures used).
Example
For the array [1,4,2,10,23,3,1,0,20] and k=4:
- Initial sum: 1+4+2+10 =17.
- Next window:17-1+23=39 (max becomes39).
- Next:39-4+3=38.
- Next:38-2+1=37.
- Next:37-10+0=27.
- Next:27-23+20=24.
- The maximum sum is 39.
This approach is optimal for the problem and works efficiently even for large arrays. It leverages the sliding window to minimize redundant calculations, making it a go-to method for subarray sum problems of fixed length.


作者声明:本文包含人工智能生成内容。