Sum of K Subarrays With Length at Least M - Problem

You are given an integer array nums and two integers, k and m. Return the maximum sum of k non-overlapping subarrays of nums, where each subarray has a length of at least m.

A subarray is a contiguous part of an array. Two subarrays are non-overlapping if they do not share any elements.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,-2,3,4,-1,2], k = 2, m = 2
Output: 8
💡 Note: Choose subarrays [3,4] with sum 7 and [-1,2] with sum 1. Total maximum sum is 7 + 1 = 8.
Example 2 — Minimum Length
$ Input: nums = [2,-1,3,4], k = 1, m = 3
Output: 6
💡 Note: Only one subarray needed with length ≥ 3. Choose [-1,3,4] with sum 6, which is better than [2,-1,3] with sum 4.
Example 3 — All Negative
$ Input: nums = [-1,-2,-3], k = 1, m = 2
Output: -3
💡 Note: Must choose one subarray of length ≥ 2. Best option is [-1,-2] with sum -3.

Constraints

  • 1 ≤ k ≤ nums.length
  • 1 ≤ m ≤ nums.length
  • k × m ≤ nums.length
  • 1 ≤ nums.length ≤ 1000
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Sum of K Subarrays With Length at Least MFind k=2 non-overlapping subarrays, each with length ≥ m=21-234-12012345Subarray 1Sum: 3 + 4 = 7Subarray 2Sum: -1 + 2 = 1Both subarrays have length ≥ 2 and are non-overlappingMaximum Sum: 7 + 1 = 8
Understanding the Visualization
1
Input
Array [1,-2,3,4,-1,2], k=2 subarrays, each length ≥ m=2
2
Process
Find k non-overlapping subarrays with length ≥ m that maximize sum
3
Output
Maximum possible sum: 8 (from subarrays [3,4] and [-1,2])
Key Takeaway
🎯 Key Insight: Use dynamic programming to efficiently explore all valid combinations of k non-overlapping subarrays
Asked in
Google 15 Amazon 12 Microsoft 8
12.8K Views
Medium Frequency
~35 min Avg. Time
456 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