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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code