Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
You are given an integer array nums with length n.
The cost of a subarray nums[l..r], where 0 <= l <= r < n, is defined as:
cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (−1)r − l
Your task is to split nums into subarrays such that the total cost 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:
cost(0, i1) + cost(i1 + 1, i2) + ... + cost(ik − 1 + 1, n − 1)
Return an integer denoting the maximum total cost of the subarrays after splitting the array optimally.
Note: If nums is not split into subarrays, i.e. k = 1, the total cost is simply cost(0, n - 1).
Example 1:
Input: nums = [1,-2,3,4]
Output: 10
Explanation:
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.
Example 2:
Input: nums = [1,-1,1,-1]
Output: 4
Explanation:
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.
Example 3:
Input: nums = [0]
Output: 0
Explanation:
We cannot split the array further, so the answer is 0.
Example 4:
Input: nums = [1,-1]
Output: 2
Explanation:
Selecting the whole array gives a total cost of 1 + 1 = 2, which is the maximum.
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 109Problem summary: You are given an integer array nums with length n. The cost of a subarray nums[l..r], where 0 <= l <= r < n, is defined as: cost(l, r) = nums[l] - nums[l + 1] + ... + nums[r] * (−1)r − l Your task is to split nums into subarrays such that the total cost 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: cost(0, i1) + cost(i1 + 1, i2) + ... + cost(ik − 1 + 1, n − 1) Return an integer denoting the maximum total cost of the subarrays after splitting the array optimally. Note: If nums is not split into subarrays, i.e. k = 1, the total cost is simply cost(0, n - 1).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming
[1,-2,3,4]
[1,-1,1,-1]
[0]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3196: Maximize Total Cost of Alternating Subarrays
class Solution {
private Long[][] f;
private int[] nums;
private int n;
public long maximumTotalCost(int[] nums) {
n = nums.length;
this.nums = nums;
f = new Long[n][2];
return dfs(0, 0);
}
private long dfs(int i, int j) {
if (i >= n) {
return 0;
}
if (f[i][j] != null) {
return f[i][j];
}
f[i][j] = nums[i] + dfs(i + 1, 1);
if (j == 1) {
f[i][j] = Math.max(f[i][j], -nums[i] + dfs(i + 1, 0));
}
return f[i][j];
}
}
// Accepted solution for LeetCode #3196: Maximize Total Cost of Alternating Subarrays
func maximumTotalCost(nums []int) int64 {
n := len(nums)
f := make([][2]int64, n)
for i := range f {
f[i] = [2]int64{-1e18, -1e18}
}
var dfs func(int, int) int64
dfs = func(i, j int) int64 {
if i >= n {
return 0
}
if f[i][j] != -1e18 {
return f[i][j]
}
f[i][j] = int64(nums[i]) + dfs(i+1, 1)
if j > 0 {
f[i][j] = max(f[i][j], int64(-nums[i])+dfs(i+1, 0))
}
return f[i][j]
}
return dfs(0, 0)
}
# Accepted solution for LeetCode #3196: Maximize Total Cost of Alternating Subarrays
class Solution:
def maximumTotalCost(self, nums: List[int]) -> int:
@cache
def dfs(i: int, j: int) -> int:
if i >= len(nums):
return 0
ans = nums[i] + dfs(i + 1, 1)
if j == 1:
ans = max(ans, -nums[i] + dfs(i + 1, 0))
return ans
return dfs(0, 0)
// Accepted solution for LeetCode #3196: Maximize Total Cost of Alternating Subarrays
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3196: Maximize Total Cost of Alternating Subarrays
// class Solution {
// private Long[][] f;
// private int[] nums;
// private int n;
//
// public long maximumTotalCost(int[] nums) {
// n = nums.length;
// this.nums = nums;
// f = new Long[n][2];
// return dfs(0, 0);
// }
//
// private long dfs(int i, int j) {
// if (i >= n) {
// return 0;
// }
// if (f[i][j] != null) {
// return f[i][j];
// }
// f[i][j] = nums[i] + dfs(i + 1, 1);
// if (j == 1) {
// f[i][j] = Math.max(f[i][j], -nums[i] + dfs(i + 1, 0));
// }
// return f[i][j];
// }
// }
// Accepted solution for LeetCode #3196: Maximize Total Cost of Alternating Subarrays
function maximumTotalCost(nums: number[]): number {
const n = nums.length;
const f: number[][] = Array.from({ length: n }, () => Array(2).fill(-Infinity));
const dfs = (i: number, j: number): number => {
if (i >= n) {
return 0;
}
if (f[i][j] !== -Infinity) {
return f[i][j];
}
f[i][j] = nums[i] + dfs(i + 1, 1);
if (j) {
f[i][j] = Math.max(f[i][j], -nums[i] + dfs(i + 1, 0));
}
return f[i][j];
};
return dfs(0, 0);
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.