#3826

Minimum Partition Score

Hard
ArrayDivide and ConquerDynamic ProgrammingQueuePrefix SumMonotonic QueueDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

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

Intuition

Time O(k * n²)Space O(n)

Using dynamic programming, we can build up the solution by calculating the minimum score for smaller subproblems, leveraging previously computed results to avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP table where dp[k][i] represents the minimum score for partitioning the first i elements into k subarrays.
  2. 2Step 2: Calculate prefix sums to efficiently compute subarray sums.
  3. 3Step 3: Use a nested loop to fill the DP table, minimizing the score by considering all possible previous partitions.
solution.py12 lines
1def minPartitionScore(nums, k):
2    n = len(nums)
3    prefix = [0] * (n + 1)
4    for i in range(n): prefix[i + 1] = prefix[i] + nums[i]
5    dp = [[float('inf')] * (n + 1) for _ in range(k + 1)]
6    dp[0][0] = 0
7    for i in range(1, n + 1):
8        for j in range(1, k + 1):
9            for p in range(j - 1, i):
10                sumArr = prefix[i] - prefix[p]
11                dp[j][i] = min(dp[j][i], dp[j - 1][p] + sumArr * (sumArr + 1) // 2)
12    return dp[k][n]

Complexity note: The complexity arises from filling the DP table, where each entry requires iterating over previous partitions, leading to a quadratic factor.

  • 1Dynamic programming is effective for partitioning problems.
  • 2Prefix sums optimize subarray sum calculations.

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