1. Max Sum Subarray of Size K
EasyProblem Statement
Given an array of integers and an integer k
, return the maximum sum of any contiguous subarray of size k
.
Function Signature
# Day 12 – Sliding Window
# Complete the function as per the problem statement.
def max_sum_subarray(nums, k):
pass
// Day 12 – Sliding Window
// Complete the function as per the problem statement.
function maxSumSubarray(nums, k) {
// TODO
}
export { maxSumSubarray };
Input/Output Format
Input: Array nums
of integers, integer k
Output: Integer representing the maximum sum
Constraints
1 ≤ k ≤ n ≤ 200,000
-10,000 ≤ nums[i] ≤ 10,000
Examples
Input:
nums = [2, 1, 5, 1, 3, 2], k = 3
Output:
9
Explanation: Window [5, 1, 3] has maximum sum of 9
Input:
nums = [2, 3, 4, 1, 5], k = 2
Output:
7
Explanation: Window [3, 4] has maximum sum of 7
Edge Cases
- All negative numbers
- k equals array length
- Single element array
Hint 1: Use sliding window technique - calculate sum of first k elements, then slide the window.
Hint 2: When sliding, subtract the element going out and add the element coming in.
Hint 3: Keep track of maximum sum seen so far.
Sample Tests
Case | Input | Expected | Notes |
---|---|---|---|
1 | [1,2,3,4], k=2 | 7 | Basic case |
2 | [-1,-2,-3], k=2 | -3 | All negative |
3 | [5], k=1 | 5 | Single element |
Acceptance Criteria
- Time complexity: O(n)
- Space complexity: O(1)
- Handles all edge cases correctly