Approach
Depth-first search
For Partition Array Into Two Arrays to Minimize Sum Difference, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 44 lines of Python from the credited upstream file 2035.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def minimumDifference(self, nums: list[int]) -> int:3 n = len(nums) 24 summ = sum(nums)5 goal = summ 26 lNums = nums[:n]7 rNums = nums[n:]8 ans = abs(sum(lNums) - sum(rNums))9 lSums = [[] for _ in range(n + 1)]10 rSums = [[] for _ in range(n + 1)]11 12 def dfs(13 arr: list[int],14 i: int,15 count: int,16 path: int,17 sums: list[list[int]]18 ):19 if i == len(arr):20 sums[count].append(path)21 return22 dfs(arr, i + 1, count + 1, path + arr[i], sums)23 dfs(arr, i + 1, count, path, sums)24 25 dfs(lNums, 0, 0, 0, lSums)26 dfs(rNums, 0, 0, 0, rSums)27 28 for lCount in range(n):29 l = lSums[lCount]30 r = rSums[n - lCount]31 r.sort()32 for lSum in l:33 i = bisect_left(r, goal - lSum)34 if i < len(r):35 sumPartOne = summ - lSum - r[i]36 sumPartTwo = summ - sumPartOne37 ans = min(ans, abs(sumPartOne - sumPartTwo))38 if i > 0:39 sumPartOne = summ - lSum - r[i - 1]40 sumPartTwo = summ - sumPartOne41 ans = min(ans, abs(sumPartOne - sumPartTwo))42 43 return ans44