#Write a program to find the maximum sum of a subarray within a given list,
#where the subarray length is at most k.
def max_subarray_sum(nums, k):
if k <= 0 or len(nums) == 0:
return 0
max_sum = float('-inf')
current_sum = 0
start = 0
for end, num in enumerate(nums):
current_sum += num
if end - start + 1 > k:
current_sum -= nums[start]
start += 1
if end - start + 1 == k:
max_sum = max(max_sum, current_sum)
return max_sum
# Example usage
nums = [1, 4, 2, 10, 2, 3, 1, 0, 20]
k = 4
print(max_subarray_sum(nums, k)) # 24
To embed this program on your website, copy the following code and paste it into your website's HTML: