#3473
Sum of K Subarrays With Length at Least M
MediumArrayDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * k) |
| Space | O(1) | O(n * k) |
💡
Intuition
Time O(n * k)Space O(n * k)
We can use dynamic programming and prefix sums to efficiently calculate the maximum sum of k non-overlapping subarrays. This reduces redundant calculations.
⚙️
Algorithm
3 steps- 1Step 1: Calculate prefix sums to quickly get subarray sums.
- 2Step 2: Use a DP array where dp[i][j] represents the max sum of j subarrays using the first i elements.
- 3Step 3: For each position, update the DP table considering the last subarray ends at that position.
solution.py11 lines
1def maxSum(nums, k, m):
2 n = len(nums)
3 prefix = [0] * (n + 1)
4 for i in range(n): prefix[i + 1] = prefix[i] + nums[i]
5 dp = [[float('-inf')] * (k + 1) for _ in range(n + 1)]
6 dp[0][0] = 0
7 for j in range(1, k + 1):
8 for i in range(m, n + 1):
9 for p in range(i - m + 1):
10 dp[i][j] = max(dp[i][j], dp[p][j - 1] + prefix[i] - prefix[p])
11 return max(dp[n])ℹ
Complexity note: The DP approach iterates through n and k, leading to O(n * k) complexity.
- 1Subarrays must be non-overlapping.
- 2Prefix sums allow quick sum calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.