To solve this problem, we need to find the maximum sum of a subarray with a fixed length ( k ). The sliding window technique is ideal here as it allows us to compute the result efficiently in linear time.
Approach
The sliding window approach works by maintaining a window of size ( k ) and sliding it across the array. Here are the key steps:
- Initial Window Sum: Calculate the sum of the first ( k ) elements (initial window).
- Slide the Window: For each subsequent element:
- Subtract the element that is sliding out of the window (leftmost element of the previous window).
- Add the new element that is sliding into the window (next element to the right).
- Track Maximum Sum: Keep updating the maximum sum whenever the current window sum is greater than the previous maximum.
Solution Code
def max_subarray_sum(arr, k):
n = len(arr)
if n < k or k <= 0:
return 0 # Handle invalid inputs
# Calculate initial 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, which takes ( O(k) ) time.
- Sliding: For each element from index ( k ) to the end of the array, we adjust the current sum by adding the new element and subtracting the element that is no longer in the window. This step takes ( O(n - k) ) time.
- Efficiency: The overall time complexity is ( O(n) ) (since ( k \leq n )), and the space complexity is ( O(1) ) as we only use a few variables to track sums.
Example Usage
Let's test the function with an example:
arr = [1, 4, 2, 10, 23, 3, 1, 0, 20]
k = 4
print(max_subarray_sum(arr, k)) # Output: 39 (sum of [4,2,10,23])
This function efficiently computes the desired result and handles edge cases like invalid inputs (e.g., ( k ) larger than the array length or non-positive ( k )).
Answer: The Python script to calculate the maximum sum of a subarray with length ( k ) is as provided above. The final answer is the function itself, which returns the maximum sum for any valid input. For the given problem context, the code is the solution.
def max_subarray_sum(arr, k):
n = len(arr)
if n < k or k <= 0:
return 0
current_sum = sum(arr[:k])
max_sum = current_sum
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


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