LeetCode Challenge Day 73 β Max Subarray Sum With Length Divisible by K
Nitin Ahirwal / November 27, 2025
Hey folks π
This is Day 73 of my LeetCode streak π
Today's problem is Max Subarray Sum With Length Divisible by K β a clean and elegant prefix-sum-based problem leveraging modulo arithmetic.
π Problem Statement
Given an array nums and an integer k, return the maximum subarray sum such that the length of the subarray is divisible by k.
A subarray qualifies only if:
(subarray_end - subarray_start + 1) % k === 0
π‘ Intuition
To get subarrays whose lengths are divisible by k, we use a key observation:
β‘οΈ If two prefix sums appear at indices i and j where:
(i - j) % k === 0
then the subarray between them has length divisible by k.
This leads to a powerful idea:
-
Group prefix sums by their index % k.
-
For each remainder
r, store the minimum prefix sum seen so far. -
At index
i, with prefixprefand residuer, the best subarray ending here is:
pref - minPref[r]
π Approach
-
Maintain a running prefix sum
pref. -
Track an array
minPref[k]storing minimum prefix sum for each residue class. -
Initialize
minPref[0] = 0for the empty prefix. -
For each index
i:-
Compute
r = i % k -
If we have a previous prefix with the same
r, compute a candidate maximum. -
Update
minPref[r]with the smallest prefix sum so far.
-
This reduces the problem to simple arithmetic while ensuring O(n) performance.
β±οΈ Complexity Analysis
|Complexity|Value| |---|---| |Time|O(n)| |Space|O(k)|
π§βπ» Code (JavaScript)
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxSubarraySum = function(nums, k) {
const n = nums.length;
const minPref = new Array(k).fill(Number.POSITIVE_INFINITY);
minPref[0] = 0;
let pref = 0;
let ans = Number.NEGATIVE_INFINITY;
for (let i = 1; i <= n; i++) {
pref += nums[i - 1];
const r = i % k;
if (minPref[r] !== Number.POSITIVE_INFINITY) {
const candidate = pref - minPref[r];
if (candidate > ans) ans = candidate;
}
if (pref < minPref[r]) minPref[r] = pref;
}
return ans;
};
π― Reflection
This problem elegantly demonstrates how prefix sums + modulo arithmetic can simplify constraints involving subarray lengths.
-
β Avoids brute-force O(nΒ²)
-
β Only
kprefix values tracked -
β Clean and efficient O(n) solution
That's it for Day 73 of my LeetCode challenge πͺ
Catch you tomorrow!
Happy Coding π¨βπ»