Maximum Strength of K Disjoint Subarrays - Problem

You are given an array of integers nums with length n, and a positive odd integer k.

Select exactly k disjoint subarrays sub₁, sub₂, ..., subₖ from nums such that the last element of subᵢ appears before the first element of subᵢ₊₁ for all 1 ≤ i ≤ k-1.

The goal is to maximize their combined strength. The strength of the selected subarrays is defined as:

strength = k × sum(sub₁) - (k-1) × sum(sub₂) + (k-2) × sum(sub₃) - ... - 2 × sum(subₖ₋₁) + sum(subₖ)

where sum(subᵢ) is the sum of the elements in the i-th subarray.

Return the maximum possible strength that can be obtained from selecting exactly k disjoint subarrays from nums.

Note: The chosen subarrays don't need to cover the entire array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,5,-3,2,4], k = 3
Output: 13
💡 Note: Select subarrays [1], [-3], [4]. Strength = 3×1 - 2×(-3) + 1×4 = 3 + 6 + 4 = 13
Example 2 — Longer Subarrays
$ Input: nums = [5,-2,3,1], k = 1
Output: 7
💡 Note: Select subarray [5,-2,3,1] with sum 7. Strength = 1×7 = 7
Example 3 — Minimum k
$ Input: nums = [8,-4], k = 1
Output: 8
💡 Note: Select subarray [8]. Strength = 1×8 = 8

Constraints

  • 1 ≤ nums.length ≤ 104
  • 1 ≤ k ≤ nums.length
  • k is odd
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Maximum Strength of K Disjoint Subarrays INPUT nums = [1, 5, -3, 2, 4] 1 i=0 5 i=1 -3 i=2 2 i=3 4 i=4 Parameters k = 3 (odd integer) Strength Formula k*sum(sub1) - (k-1)*sum(sub2) + (k-2)*sum(sub3) Goal: Select k=3 disjoint subarrays to maximize strength ALGORITHM (DP) 1 Define DP State dp[i][j] = max strength using first i elements, j subarrays 2 Compute Coefficients coef[j] = k-j+1 if odd j coef[j] = -(k-j+1) if even j 3 Transition Extend current subarray or start new subarray at i 4 Track Maximum Answer = max(dp[i][k]) for all valid i Optimal Selection 1 5 -3 2 4 sub1=[1,5] sub2=[2] sub3=[4] 3*(6) - 2*(2) + 1*(4) = 13 FINAL RESULT Optimal k=3 Disjoint Subarrays: Subarray 1: [1, 5] sum = 6, coef = +3 Subarray 2: [2] sum = 2, coef = -2 Subarray 3: [4] sum = 4, coef = +1 3*6 - 2*2 + 1*4 = 18 - 4 + 4 = 18 Maximum Strength Output: 13 Key Insight: Use 2D DP where dp[i][j] tracks maximum strength ending at index i with j subarrays selected. The alternating signs (+/-) in the formula are handled by precomputing coefficients based on subarray index. At each position, decide to extend current subarray or start a new one. Time: O(n*k), Space: O(n*k). TutorialsPoint - Maximum Strength of K Disjoint Subarrays | Dynamic Programming Approach
Asked in
Google 35 Meta 28 Amazon 22
23.1K Views
Medium Frequency
~35 min Avg. Time
856 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