#3196

Maximize Total Cost of Alternating Subarrays

Medium
ArrayDynamic ProgrammingDynamic ProgrammingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to keep track of the maximum cost at each index while considering the alternating sum. This avoids recalculating costs for overlapping subarrays.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[i] represents the maximum cost ending at index i.
  2. 2Step 2: Iterate through the array and calculate the cost for each index based on the previous index's cost.
  3. 3Step 3: Update the maximum total cost when a new subarray starts.
solution.py17 lines
1# Full working Python code
2
3def maxCost(nums):
4    n = len(nums)
5    if n == 1:
6        return 0
7    dp = [0] * n
8    dp[0] = nums[0]
9    max_cost = 0
10    for i in range(1, n):
11        dp[i] = dp[i - 1] + (nums[i] if i % 2 == 1 else -nums[i])
12        if i > 1:
13            max_cost = max(max_cost, dp[i])
14    return max_cost
15
16# Example usage
17print(maxCost([1, -2, 3, 4]))  # Output: 10

Complexity note: The time complexity is O(n) because we only iterate through the array once, and the space complexity is O(n) due to the DP array used to store intermediate results.

  • 1Understanding alternating sums is crucial.
  • 2Dynamic programming helps to optimize overlapping subproblems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.