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
Maximum Subarray Sum With Length Divisible by K INPUT nums array: 0 1 2 3 4 1 -3 2 1 -1 k = 2 Find max sum subarray with length divisible by k Valid lengths: 2, 4 Possible Subarrays (len=2): [1,-3]=−2 [-3,2]=−1 [2,1]=3 [1,-1]=0 (len=4): [1,-3,2,1]=1 ALGORITHM STEPS 1 Prefix Sum by Mod Track prefix[i] % k groups 2 Store Max Prefix For each mod value, keep max 3 Compute Differences Sum = prefix[j] - prefix[i] 4 Track Maximum Update max when same mod Prefix Sum Computation i pre mod max[mod] result 0 0 0 {0:0} - 1 1 1 {1:1} - 2 -2 0 {0:0} -2 3 0 0 {0:0} 0 4 3 1 {1:1} 3 FINAL RESULT Maximum Subarray Found: 1 -3 2 1 -1 indices 2-3 Output: 3 Subarray [2, 1] Sum: 2 + 1 = 3 Length = 2 2 % 2 = 0 ... OK Key Insight: If two prefix sums have the same remainder when divided by k, their difference represents a subarray with length divisible by k. Track max prefix sum for each mod value to find optimal subarray in O(n) time. TutorialsPoint - Maximum Subarray Sum With Length Divisible by K | Optimal Solution Time: O(n) | Space: O(k)
Asked in
Google 45 Amazon 32 Microsoft 28
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen