Problem solution · Python

Minimum Partition Score

Minimum Partition Score: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
95 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Minimum Partition Score, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 95 lines of Python from the credited upstream file minimum-partition-score.py.
  • The implementation visibly relies on sequence storage, work queue, cached states.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMinimum Partition Score · PythonPython
Use this to learn the idea, then write your own version.
# 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 trickclass 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)        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 trickclass 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] 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗