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: 35
💡 Note: Select subarray [5,-2,3,1] with sum 7. Strength = 1×7 = 7. Wait, this should be 5×1 = 5 for just [5]. Actually, best is [5,-2,3,1] = 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: Select k=3 Disjoint Subarrays15-324×3×(-2)×1sub₁sub₂sub₃Strength = 3×1 + (-2)×(-3) + 1×4 = 3 + 6 + 4 = 13Maximum Strength: 13
Understanding the Visualization
1
Input
Array [1,5,-3,2,4] with k=3 subarrays needed
2
Selection
Choose 3 disjoint subarrays with weights 3, -2, 1
3
Calculation
Strength = 3×1 - 2×(-3) + 1×4 = 13
Key Takeaway
🎯 Key Insight: The alternating weight pattern means we want maximum positive subarrays for odd positions and minimum (most negative) for even positions
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