Your task is to splitnums into subarrays such that the totalcost of the subarrays is maximized , ensuring each element belongs to
exactly one subarray.
Formally, if nums is split into k subarrays, where k > 1, at indices
i1, i2, ..., ik − 1, where 0 <= i1 < i2 < ... < ik - 1 < n - 1, then the total cost will be:
Input: nums =[1,-2,3,4]Output: 10Explanation:
One way to maximize the total cost is by splitting `[1, -2, 3, 4]` into
subarrays `[1, -2, 3]` and `[4]`. The total cost will be `(1 + 2 + 3) + 4 =
10`.
Input: nums =[1,-1,1,-1]Output: 4Explanation:
One way to maximize the total cost is by splitting `[1, -1, 1, -1]` into
subarrays `[1, -1]` and `[1, -1]`. The total cost will be `(1 + 1) + (1 + 1) =
4`.
Input: nums =[0]Output: 0Explanation:
We cannot split the array further, so the answer is0.#### Example 4Input: nums =[1,-1]Output: 2Explanation:
Selecting the whole array gives a total cost of `1 + 1 = 2`, which is the
maximum.
The cost function alternates the sign for each element in a subarray, starting with positive. This is similar to maximizing the sum of subarrays where the sign alternates. We can use dynamic programming to keep track of the best possible sum ending at each index, considering the alternation.
classSolution {
publiclongmaximumCost(int[] nums) {
long ans = Long.MIN_VALUE, even = 0, odd = Long.MIN_VALUE;
for (int x : nums) {
long newEven = Math.max(even + x, odd - x);
long newOdd = Math.max(odd, even - x);
even = newEven;
odd = newOdd;
ans = Math.max(ans, even);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funmaximumCost(nums: IntArray): Long {
var ans = Long.MIN_VALUE
var even = 0Lvar odd = Long.MIN_VALUE
for (x in nums) {
val newEven = maxOf(even + x, odd - x)
val newOdd = maxOf(odd, even - x)
even = newEven
odd = newOdd
ans = maxOf(ans, even)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defmaximumCost(self, nums: list[int]) -> int:
ans = float('-inf')
even =0 odd = float('-inf')
for x in nums:
new_even = max(even + x, odd - x)
new_odd = max(odd, even - x)
even, odd = new_even, new_odd
ans = max(ans, even)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmaximum_cost(nums: Vec<i32>) -> i64 {
letmut ans =i64::MIN;
letmut even =0i64;
letmut odd =i64::MIN;
for&x in&nums {
let nx = x asi64;
let new_even = even.max(odd - nx) + nx;
let new_odd = odd.max(even - nx);
even = new_even;
odd = new_odd;
ans = ans.max(even);
}
ans
}
}