#3500

Minimum Cost to Divide Array Into Subarrays

Hard
ArrayDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
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)

Using dynamic programming, we can build a solution by calculating the minimum cost for each suffix of the array, leveraging previously computed results to avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a dp array where dp[i] represents the minimum cost for the suffix starting at index i.
  2. 2Step 2: Iterate backwards through the array, calculating the cost for each possible subarray ending at the current index.
  3. 3Step 3: Update dp[i] based on the minimum cost found for all subarrays starting from i.
solution.py12 lines
1def minCost(nums, cost, k):
2    n = len(nums)
3    dp = [float('inf')] * (n + 1)
4    dp[n] = 0
5    for i in range(n - 1, -1, -1):
6        subarray_sum = 0
7        subarray_cost = 0
8        for j in range(i, n):
9            subarray_sum += nums[j]
10            subarray_cost += cost[j]
11            dp[i] = min(dp[i], (subarray_sum + k * (n - j)) * subarray_cost + dp[j + 1])
12    return dp[0]

Complexity note: The outer loop runs n times, and the inner loop can run up to n times, leading to O(n²) time complexity, while dp array uses O(n) space.

  • 1Dynamic programming helps to break down the problem into manageable subproblems.
  • 2Cost accumulation can be efficiently calculated using prefix sums.

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