#3010

Divide an Array Into Subarrays With Minimum Cost I

Easy
ArraySortingEnumerationDynamic ProgrammingArray
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 efficiently calculate the minimum cost by storing intermediate results. This avoids redundant calculations and significantly reduces the number of operations needed.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array to store the minimum cost for splitting the array into k subarrays.
  2. 2Step 2: Iterate through the array and update the DP array based on previous results and the current element's cost.
  3. 3Step 3: Return the minimum cost for 3 subarrays.
solution.py10 lines
1def minCost(nums):
2    n = len(nums)
3    dp = [[float('inf')] * 4 for _ in range(n)]
4    for i in range(n):
5        dp[i][1] = nums[0] if i == 0 else min(dp[i-1][1], nums[0])
6    for k in range(2, 4):
7        for i in range(n):
8            for j in range(i):
9                dp[i][k] = min(dp[i][k], dp[j][k-1] + nums[i])
10    return dp[n-1][3]

Complexity note: The time complexity is O(n³) due to the nested loops for filling the DP table, but this is significantly more efficient than the brute force approach.

  • 1The cost of a subarray is determined solely by its first element.
  • 2Dynamic programming can significantly reduce redundant calculations.

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