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 M INPUT nums array: 1 i=0 -2 i=1 3 i=2 4 i=3 -1 i=4 2 i=5 Parameters: k = 2 m = 2 (2 subarrays) (min length 2) Find k=2 non-overlapping subarrays, each with length >= m=2 ALGORITHM STEPS 1 Define DP State dp[i][j] = max sum using j subarrays in first i elems 2 Prefix Sum Compute prefix sums for O(1) subarray sum queries 3 Transition For each position, try starting new subarray of length >= m or skip 4 Track Maximum Use auxiliary array to track best dp[i][j-1] Optimal Subarrays Found: [3,4] = 7 [-1,2] = 1 Total: 7 + 1 = 8 FINAL RESULT Selected subarrays highlighted: 1 -2 3 4 -1 2 Subarray 1 Subarray 2 Calculation: Subarray 1: [3,4] Sum = 3 + 4 = 7 Subarray 2: [-1,2] Sum = -1 + 2 = 1 OUTPUT 8 OK - Maximum sum achieved! Key Insight: Use dynamic programming with state dp[i][j] representing the maximum sum achievable using exactly j non-overlapping subarrays from the first i elements. Track the best previous state to enable O(n*k) transitions. The minimum length constraint m is enforced when starting each new subarray. TutorialsPoint - Sum of K Subarrays With Length at Least M | DP Approach
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