Maximum Strength of K Disjoint Subarrays Problem
Description
LeetCode Problem 3077.
You are given an array of integers nums with length n, and a positive odd integer k.
Select exactly k disjoint subarrays sub_1, sub_2, ..., sub_k from nums such that the last element of sub_i appears before the first element of sub_({i+1}) 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_1)- (k - 1) * sum(sub_2) + (k - 2) * sum(sub_3) - ... - 2 * sum(sub_({k-1})) + sum(sub_k)
where sum(sub_i) 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 that the chosen subarrays don't need to cover the entire array.
Example 1:
Input: nums = [1,2,3,-1,2], k = 3
Output: 22
Explanation:
The best possible way to select 3 subarrays is: nums[0..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:
strength = 3 * (1 + 2 + 3) - 2 * (-1) + 2 = 22
Example 2:
Input: nums = [12,-2,-2,-2,-2], k = 5
Output: 64
Explanation:
The only possible way to select 5 disjoint subarrays is: nums[0..0], nums[1..1], nums[2..2], nums[3..3], and nums[4..4]. The strength is calculated as follows:
strength = 5 * 12 - 4 * (-2) + 3 * (-2) - 2 * (-2) + (-2) = 64
Example 3:
Input: nums = [-1,-2,-3], k = 1
Output: -1
Explanation:
The best possible way to select 1 subarray is: nums[0..0]. The strength is -1.
Constraints:
1 <= n <= 10^4-10^9 <= nums[i] <= 10^91 <= k <= n1 <= n * k <= 10^6kis odd.
Solution
Approach: Dynamic Programming
If nums[i-1] lies in the j-th chosen subarray, it adds sign * nums[i-1] * (k - j + 1) to the strength, where sign is +1 for odd j and -1 for even j.
Let f[i][j][0] be the best value using the first i numbers with j subarrays when number i is not chosen, and f[i][j][1] when it is chosen. Start with f[0][0][0] = 0 and everything else minus infinity. Not choosing number i: f[i][j][0] = max(f[i-1][j][0], f[i-1][j][1]). Choosing it either extends the current subarray, f[i-1][j][1] + val, or starts subarray j, max(f[i-1][j-1][0], f[i-1][j-1][1]) + val, where val is the contribution above. The answer is max(f[n][k][0], f[n][k][1]).
Complexity: O(nk) time and O(nk) extra space, where n is the length of nums.
from math import inf
class Solution:
def maximumStrength(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [[[-inf, -inf] for _ in range(k + 1)] for _ in range(n + 1)]
f[0][0][0] = 0
for i, x in enumerate(nums, 1):
for j in range(k + 1):
sign = 1 if j & 1 else -1
f[i][j][0] = max(f[i - 1][j][0], f[i - 1][j][1])
f[i][j][1] = max(f[i][j][1], f[i - 1][j][1] + sign * x * (k - j + 1))
if j:
f[i][j][1] = max(
f[i][j][1], max(f[i - 1][j - 1]) + sign * x * (k - j + 1)
)
return max(f[n][k])