Problem solution · Python

Divide an Array Into Subarrays With Minimum Cost II

Divide an Array Into Subarrays With Minimum Cost II: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Direct simulation
Source
walkccc LeetCode Solutions
Length
49 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

Direct simulation

For Divide an Array Into Subarrays With Minimum Cost II, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 49 lines of Python from the credited upstream file 3013.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.

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

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeDivide an Array Into Subarrays With Minimum Cost II · PythonPython
Use this to learn the idea, then write your own version.
from sortedcontainers import SortedList  class Solution:  def minimumCost(self, nums: list[int], k: int, dist: int) -> int:    # Equivalently, the problem is to find nums[0] + the minimum sum of the top    # k - 1 numbers in nums[i..i + dist], where i > 0 and i + dist < n.    windowSum = sum(nums[i] for i in range(1, dist + 2))    selected = SortedList(nums[i] for i in range(1, dist + 2))    candidates = SortedList()     def balance() -> int:      """      Returns the updated `windowSum` by balancing the multiset `selected` to      keep the top k - 1 numbers.      """      nonlocal windowSum      while len(selected) < k - 1:        minCandidate = candidates[0]        windowSum += minCandidate        selected.add(minCandidate)        candidates.remove(minCandidate)      while len(selected) > k - 1:        maxSelected = selected[-1]        windowSum -= maxSelected        selected.remove(maxSelected)        candidates.add(maxSelected)      return windowSum     windowSum = balance()    minWindowSum = windowSum     for i in range(dist + 2, len(nums)):      outOfScope = nums[i - dist - 1]      if outOfScope in selected:        windowSum -= outOfScope        selected.remove(outOfScope)      else:        candidates.remove(outOfScope)      if nums[i] < selected[-1]:  # nums[i] is a better number.        windowSum += nums[i]        selected.add(nums[i])      else:        candidates.add(nums[i])      windowSum = balance()      minWindowSum = min(minWindowSum, windowSum)     return nums[0] + minWindowSum 

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 ↗