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.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
You are given an integer array nums and an integer k.
Your task is to partition nums into exactly k subarrays and return an integer denoting the minimum possible score among all valid partitions.
The score of a partition is the sum of the values of all its subarrays.
The value of a subarray is defined as sumArr * (sumArr + 1) / 2, where sumArr is the sum of its elements.
Example 1:
Input: nums = [5,1,2,1], k = 2
Output: 25
Explanation:
k = 2 subarrays. One optimal partition is [5] and [1, 2, 1].sumArr = 5 and value = 5 × 6 / 2 = 15.sumArr = 1 + 2 + 1 = 4 and value = 4 × 5 / 2 = 10.15 + 10 = 25, which is the minimum possible score.Example 2:
Input: nums = [1,2,3,4], k = 1
Output: 55
Explanation:
k = 1 subarray, all elements belong to the same subarray: [1, 2, 3, 4].sumArr = 1 + 2 + 3 + 4 = 10 and value = 10 × 11 / 2 = 55.Example 3:
Input: nums = [1,1,1], k = 3
Output: 3
Explanation:
k = 3 subarrays. The only valid partition is [1], [1], [1].sumArr = 1 and value = 1 × 2 / 2 = 1.1 + 1 + 1 = 3, which is the minimum possible score.Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1041 <= k <= nums.length Problem summary: You are given an integer array nums and an integer k. Your task is to partition nums into exactly k subarrays and return an integer denoting the minimum possible score among all valid partitions. The score of a partition is the sum of the values of all its subarrays. The value of a subarray is defined as sumArr * (sumArr + 1) / 2, where sumArr is the sum of its elements.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Monotonic Queue
[5,1,2,1] 2
[1,2,3,4] 1
[1,1,1] 3
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3826: Minimum Partition Score
// Auto-generated Java example from go.
class Solution {
public void exampleSolution() {
}
}
// Reference (go):
// // Accepted solution for LeetCode #3826: Minimum Partition Score
// package main
//
// import (
// "math"
// "math/big"
// )
//
// // https://space.bilibili.com/206214
// type vec struct{ x, y int }
//
// func (a vec) sub(b vec) vec { return vec{a.x - b.x, a.y - b.y} }
// func (a vec) dot(b vec) int { return a.x*b.x + a.y*b.y }
// func (a vec) det(b vec) int { return a.x*b.y - a.y*b.x } // 如果乘法会溢出,用 detCmp
// func (a vec) detCmp(b vec) int {
// v := new(big.Int).Mul(big.NewInt(int64(a.x)), big.NewInt(int64(b.y)))
// w := new(big.Int).Mul(big.NewInt(int64(a.y)), big.NewInt(int64(b.x)))
// return v.Cmp(w)
// }
//
// func minPartitionScore(nums []int, k int) int64 {
// n := len(nums)
// sum := make([]int, n+1)
// for i, x := range nums {
// sum[i+1] = sum[i] + x
// }
//
// f := make([]int, n+1)
// for i := 1; i <= n; i++ {
// f[i] = math.MaxInt / 2
// }
//
// for K := 1; K <= k; K++ {
// s := sum[K-1]
// q := []vec{{s, f[K-1] + s*s - s}}
// for i := K; i <= n-(k-K); i++ {
// s = sum[i]
// p := vec{-2 * s, 1}
// for len(q) > 1 && p.dot(q[0]) >= p.dot(q[1]) {
// q = q[1:]
// }
//
// v := vec{s, f[i] + s*s - s}
// f[i] = p.dot(q[0]) + s*s + s
//
// // 读者可以把 detCmp 改成 det 感受下这个算法的效率
// // 目前 det 也能过,可以试试 hack 一下
// for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).detCmp(v.sub(q[len(q)-1])) <= 0 {
// q = q[:len(q)-1]
// }
// q = append(q, v)
// }
// }
//
// return int64(f[n] / 2)
// }
//
// //func main() {
// // a := make([]int, 1000)
// // for i := range a {
// // a[i] = 1e4
// // }
// // fmt.Println(minPartitionScore(a, 2))
// //}
// Accepted solution for LeetCode #3826: Minimum Partition Score
package main
import (
"math"
"math/big"
)
// https://space.bilibili.com/206214
type vec struct{ x, y int }
func (a vec) sub(b vec) vec { return vec{a.x - b.x, a.y - b.y} }
func (a vec) dot(b vec) int { return a.x*b.x + a.y*b.y }
func (a vec) det(b vec) int { return a.x*b.y - a.y*b.x } // 如果乘法会溢出,用 detCmp
func (a vec) detCmp(b vec) int {
v := new(big.Int).Mul(big.NewInt(int64(a.x)), big.NewInt(int64(b.y)))
w := new(big.Int).Mul(big.NewInt(int64(a.y)), big.NewInt(int64(b.x)))
return v.Cmp(w)
}
func minPartitionScore(nums []int, k int) int64 {
n := len(nums)
sum := make([]int, n+1)
for i, x := range nums {
sum[i+1] = sum[i] + x
}
f := make([]int, n+1)
for i := 1; i <= n; i++ {
f[i] = math.MaxInt / 2
}
for K := 1; K <= k; K++ {
s := sum[K-1]
q := []vec{{s, f[K-1] + s*s - s}}
for i := K; i <= n-(k-K); i++ {
s = sum[i]
p := vec{-2 * s, 1}
for len(q) > 1 && p.dot(q[0]) >= p.dot(q[1]) {
q = q[1:]
}
v := vec{s, f[i] + s*s - s}
f[i] = p.dot(q[0]) + s*s + s
// 读者可以把 detCmp 改成 det 感受下这个算法的效率
// 目前 det 也能过,可以试试 hack 一下
for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).detCmp(v.sub(q[len(q)-1])) <= 0 {
q = q[:len(q)-1]
}
q = append(q, v)
}
}
return int64(f[n] / 2)
}
//func main() {
// a := make([]int, 1000)
// for i := range a {
// a[i] = 1e4
// }
// fmt.Println(minPartitionScore(a, 2))
//}
# Accepted solution for LeetCode #3826: Minimum Partition Score
# Time: O(n * log(n * r)) = O(nlogn + nlogr), r = max(nums)
# Space: O(n)
import collections
# prefix sum, dp, convex hull trick, wqs binary search, alien trick
class Solution(object):
def minPartitionScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def binary_search(left, right, check):
while left <= right:
mid = left+(right-left)//2
if check(mid):
right = mid-1
else:
left = mid+1
return left
def check(l1, l2, l3):
return (l2[1]-l1[1])*(l2[0]-l3[0]) < (l3[1]-l2[1])*(l1[0]-l2[0])
def max_lambda():
mx, total = 0, prefix[-1]*(prefix[-1]+1)//2
for i in xrange(1, len(nums)):
c1, c2 = prefix[i], prefix[-1]-prefix[i]
mx = max(mx, total-(c1*(c1+1)//2+c2*(c2+1)//2))
return mx
def f(l):
dp = cnt = 0
hull = collections.deque([(0, 0, 0)])
for i in xrange(len(nums)):
x = prefix[i+1]
while len(hull) >= 2 and hull[0][0]*x+hull[0][1] >= hull[1][0]*x+hull[1][1]:
hull.popleft()
dp, cnt = (hull[0][0]*x+hull[0][1])+(x*x+x)//2+l, hull[0][2]+1
line = (-x, dp+(x*x-x)//2, cnt)
while len(hull) >= 2 and not check(hull[-2], hull[-1], line):
hull.pop()
hull.append(line)
return dp, cnt
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
prefix[i+1] = prefix[i]+nums[i]
mx = max_lambda()
assert(f(mx+1)[1] == 1)
l = binary_search(0, mx, lambda x: f(x)[1] <= k)
return f(l)[0]-k*l
# Time: O(n * k)
# Space: O(n)
import collections
# prefix sum, dp, convex hull trick
class Solution2(object):
def minPartitionScore(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
def check(l1, l2, l3):
return (l2[1]-l1[1])*(l2[0]-l3[0]) < (l3[1]-l2[1])*(l1[0]-l2[0])
INF = float("inf")
prefix = [0]*(len(nums)+1)
for i in xrange(len(nums)):
prefix[i+1] = prefix[i]+nums[i]
dp = [INF]*(len(nums)+1)
dp[0] = 0
for j in xrange(k):
new_dp = [INF]*(len(nums)+1)
hull = collections.deque()
for i in xrange(j, len(nums)):
if dp[i] is not INF:
x = prefix[i]
line = (-x, dp[i]+(x*x-x)//2)
while len(hull) >= 2 and not check(hull[-2], hull[-1], line):
hull.pop()
hull.append(line)
x = prefix[i+1]
while len(hull) >= 2 and hull[0][0]*x+hull[0][1] >= hull[1][0]*x+hull[1][1]:
hull.popleft()
new_dp[i+1] = hull[0][0]*x+hull[0][1]+(x*x+x)//2
dp = new_dp
return dp[-1]
// Accepted solution for LeetCode #3826: Minimum Partition Score
// Rust example auto-generated from go 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 (go):
// // Accepted solution for LeetCode #3826: Minimum Partition Score
// package main
//
// import (
// "math"
// "math/big"
// )
//
// // https://space.bilibili.com/206214
// type vec struct{ x, y int }
//
// func (a vec) sub(b vec) vec { return vec{a.x - b.x, a.y - b.y} }
// func (a vec) dot(b vec) int { return a.x*b.x + a.y*b.y }
// func (a vec) det(b vec) int { return a.x*b.y - a.y*b.x } // 如果乘法会溢出,用 detCmp
// func (a vec) detCmp(b vec) int {
// v := new(big.Int).Mul(big.NewInt(int64(a.x)), big.NewInt(int64(b.y)))
// w := new(big.Int).Mul(big.NewInt(int64(a.y)), big.NewInt(int64(b.x)))
// return v.Cmp(w)
// }
//
// func minPartitionScore(nums []int, k int) int64 {
// n := len(nums)
// sum := make([]int, n+1)
// for i, x := range nums {
// sum[i+1] = sum[i] + x
// }
//
// f := make([]int, n+1)
// for i := 1; i <= n; i++ {
// f[i] = math.MaxInt / 2
// }
//
// for K := 1; K <= k; K++ {
// s := sum[K-1]
// q := []vec{{s, f[K-1] + s*s - s}}
// for i := K; i <= n-(k-K); i++ {
// s = sum[i]
// p := vec{-2 * s, 1}
// for len(q) > 1 && p.dot(q[0]) >= p.dot(q[1]) {
// q = q[1:]
// }
//
// v := vec{s, f[i] + s*s - s}
// f[i] = p.dot(q[0]) + s*s + s
//
// // 读者可以把 detCmp 改成 det 感受下这个算法的效率
// // 目前 det 也能过,可以试试 hack 一下
// for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).detCmp(v.sub(q[len(q)-1])) <= 0 {
// q = q[:len(q)-1]
// }
// q = append(q, v)
// }
// }
//
// return int64(f[n] / 2)
// }
//
// //func main() {
// // a := make([]int, 1000)
// // for i := range a {
// // a[i] = 1e4
// // }
// // fmt.Println(minPartitionScore(a, 2))
// //}
// Accepted solution for LeetCode #3826: Minimum Partition Score
// Auto-generated TypeScript example from go.
function exampleSolution(): void {
}
// Reference (go):
// // Accepted solution for LeetCode #3826: Minimum Partition Score
// package main
//
// import (
// "math"
// "math/big"
// )
//
// // https://space.bilibili.com/206214
// type vec struct{ x, y int }
//
// func (a vec) sub(b vec) vec { return vec{a.x - b.x, a.y - b.y} }
// func (a vec) dot(b vec) int { return a.x*b.x + a.y*b.y }
// func (a vec) det(b vec) int { return a.x*b.y - a.y*b.x } // 如果乘法会溢出,用 detCmp
// func (a vec) detCmp(b vec) int {
// v := new(big.Int).Mul(big.NewInt(int64(a.x)), big.NewInt(int64(b.y)))
// w := new(big.Int).Mul(big.NewInt(int64(a.y)), big.NewInt(int64(b.x)))
// return v.Cmp(w)
// }
//
// func minPartitionScore(nums []int, k int) int64 {
// n := len(nums)
// sum := make([]int, n+1)
// for i, x := range nums {
// sum[i+1] = sum[i] + x
// }
//
// f := make([]int, n+1)
// for i := 1; i <= n; i++ {
// f[i] = math.MaxInt / 2
// }
//
// for K := 1; K <= k; K++ {
// s := sum[K-1]
// q := []vec{{s, f[K-1] + s*s - s}}
// for i := K; i <= n-(k-K); i++ {
// s = sum[i]
// p := vec{-2 * s, 1}
// for len(q) > 1 && p.dot(q[0]) >= p.dot(q[1]) {
// q = q[1:]
// }
//
// v := vec{s, f[i] + s*s - s}
// f[i] = p.dot(q[0]) + s*s + s
//
// // 读者可以把 detCmp 改成 det 感受下这个算法的效率
// // 目前 det 也能过,可以试试 hack 一下
// for len(q) > 1 && q[len(q)-1].sub(q[len(q)-2]).detCmp(v.sub(q[len(q)-1])) <= 0 {
// q = q[:len(q)-1]
// }
// q = append(q, v)
// }
// }
//
// return int64(f[n] / 2)
// }
//
// //func main() {
// // a := make([]int, 1000)
// // for i := range a {
// // a[i] = 1e4
// // }
// // fmt.Println(minPartitionScore(a, 2))
// //}
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.