Maximum Subarray Sum With Length Divisible by K - Problem

Given an array of integers nums and a positive integer k, find the maximum sum of any contiguous subarray whose length is divisible by k.

A subarray is a contiguous sequence of elements within an array. The length of a subarray must be a multiple of k (i.e., k, 2k, 3k, etc.) to be considered valid.

Example: If nums = [1, -3, 2, 1, -1] and k = 2, valid subarrays have lengths 2 or 4. The subarray [2, 1] has length 2 and sum 3, which would be the maximum.

Return the maximum sum among all valid subarrays, or 0 if no valid subarray exists.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [1, -3, 2, 1, -1], k = 2
โ€บ Output: 3
๐Ÿ’ก Note: Valid subarrays with length divisible by 2: [1,-3] (sum=-2), [-3,2] (sum=-1), [2,1] (sum=3), [1,-1] (sum=0), [1,-3,2,1] (sum=1), [-3,2,1,-1] (sum=-1). Maximum sum is 3 from subarray [2,1].
example_2.py โ€” All Negative
$ Input: nums = [-1, -2, -3], k = 2
โ€บ Output: -3
๐Ÿ’ก Note: Valid subarrays with length divisible by 2: [-1,-2] (sum=-3), [-2,-3] (sum=-5). Maximum sum is -3.
example_3.py โ€” Single Valid Subarray
$ Input: nums = [5, -2, 3], k = 3
โ€บ Output: 6
๐Ÿ’ก Note: Only one valid subarray with length divisible by 3: [5,-2,3] with length 3 and sum 6.

Constraints

  • 1 โ‰ค nums.length โ‰ค 104
  • -104 โ‰ค nums[i] โ‰ค 104
  • 1 โ‰ค k โ‰ค nums.length
  • At least one valid subarray must exist if nums.length โ‰ฅ k

Visualization

Tap to expand
๐Ÿจ Hotel Revenue Optimization (k=2 night minimum)Room 1$100Room 2-$50Room 3$80Room 4$70Room 5-$202-Night Stay: $302-Night Stay: $150 โœจ4-Night Stay: $200Prefix Sum AlgorithmCumulative Revenue:Day 1: $100Day 2: $100 + (-$50) = $50Day 3: $50 + $80 = $130Day 4: $130 + $70 = $200Day 5: $200 + (-$20) = $180Pattern Analysis (k=2):Remainder 0 positions: 2,4Remainder 1 positions: 1,3,5Best 2-night stay: Rooms 3-4Maximum Revenue: $150๐ŸŽฏ Key: Same remainder positions create valid k-length stays!
Understanding the Visualization
1
Track Daily Revenue
Calculate cumulative revenue up to each day (prefix sums)
2
Group by Stay Pattern
Group positions by their remainder when divided by k (same booking pattern)
3
Find Best Periods
For each booking pattern, find the period with maximum revenue
4
Return Maximum
Choose the booking period with the highest total revenue
Key Takeaway
๐ŸŽฏ Key Insight: By tracking prefix sums and grouping positions by their remainder when divided by k, we can efficiently find all subarrays with lengths divisible by k and identify the one with maximum sum in linear time.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
58.2K Views
Medium Frequency
~25 min Avg. Time
1.5K 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