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
- 56 lines of Java from the credited upstream file 2035.java.
- The implementation visibly relies on sequence storage.
- 3 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 public int minimumDifference(int[] nums) {3 final int n = nums.length / 2;4 final int sum = Arrays.stream(nums).sum();5 final int goal = sum / 2;6 final int[] lNums = Arrays.copyOfRange(nums, 0, n);7 final int[] rNums = Arrays.copyOfRange(nums, n, nums.length);8 int ans = Integer.MAX_VALUE;9 List<Integer>[] lSums = new List[n + 1];10 List<Integer>[] rSums = new List[n + 1];11 12 for (int i = 0; i <= n; ++i) {13 lSums[i] = new ArrayList<>();14 rSums[i] = new ArrayList<>();15 }16 17 dfs(lNums, 0, 0, 0, lSums);18 dfs(rNums, 0, 0, 0, rSums);19 20 for (int lCount = 0; lCount <= n; ++lCount) {21 List<Integer> l = lSums[lCount];22 List<Integer> r = rSums[n - lCount];23 Collections.sort(r);24 for (final int lSum : l) {25 final int i = firstGreaterEqual(r, goal - lSum);26 if (i < r.size()) {27 final int sumPartOne = sum - lSum - r.get(i);28 final int sumPartTwo = sum - sumPartOne;29 ans = Math.min(ans, Math.abs(sumPartOne - sumPartTwo));30 }31 if (i > 0) {32 final int sumPartOne = sum - lSum - r.get(i - 1);33 final int sumPartTwo = sum - sumPartOne;34 ans = Math.min(ans, Math.abs(sumPartOne - sumPartTwo));35 }36 }37 }38 39 return ans;40 }41 42 private void dfs(int[] arr, int i, int count, int path, List<Integer>[] sums) {43 if (i == arr.length) {44 sums[count].add(path);45 return;46 }47 dfs(arr, i + 1, count + 1, path + arr[i], sums);48 dfs(arr, i + 1, count, path, sums);49 }50 51 private int firstGreaterEqual(List<Integer> arr, int target) {52 final int i = Collections.binarySearch(arr, target);53 return i < 0 ? -i - 1 : i;54 }55}56