Maximum Subarray Sum With Length Divisible by K - Problem
You are given an array of integers nums and an integer k.
Return the maximum sum of a subarray of nums, such that the size of the subarray is divisible by k.
A subarray is a contiguous non-empty sequence of elements within an array.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,-3,2,1,-1], k = 2
›
Output:
3
💡 Note:
Subarray [2,1] has length 2 (divisible by k=2) and sum 2+1=3, which is the maximum possible.
Example 2 — Longer Subarray
$
Input:
nums = [-1,-2,0,2], k = 2
›
Output:
2
💡 Note:
Subarray [0,2] has length 2 (divisible by k=2) and sum 0+2=2, which is the maximum.
Example 3 — All Elements
$
Input:
nums = [1,2], k = 1
›
Output:
3
💡 Note:
Since k=1, any subarray length is divisible by k. The entire array [1,2] has sum 3.
Constraints
- 1 ≤ nums.length ≤ 105
- -104 ≤ nums[i] ≤ 104
- 1 ≤ k ≤ nums.length
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums=[1,-3,2,1,-1] and k=2
2
Process
Find all subarrays with length divisible by k=2
3
Output
Maximum sum is 3 from subarray [2,1]
Key Takeaway
🎯 Key Insight: Use prefix sums and track remainders modulo k to efficiently find subarrays with length divisible by k
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code