Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The smallest difference between two groups

Medium · Target 20 minutes · Dynamic programming · Type asked atGoogleAmazon

Given positive integers nums, divide them into two groups (either may be empty) and return the smallest possible absolute difference between the two groups' sums. (This is also the answer to "smash stones together; what is the smallest weight that can be left?".)

Examples

InputOutputWhy
nums = [2,7,4,1,8,1]1For example {8, 2, 1} = 11 and {7, 4, 1} = 12.
nums = [31,26,33,21,40]5{40, 33} = 73 and {31, 26, 21} = 78.
nums = [1,6,11,5]1{1, 5, 6} = 12 and {11}.

Constraints

  • 1 ≤ nums.length ≤ 30
  • 1 ≤ nums[i] ≤ 100

Hints

Hint 1

If one group sums to s, the difference is |total − 2s|.

Hint 2

Find every reachable subset sum up to total / 2 with the 0/1 knapsack.

Hint 3

The largest reachable s ≤ total / 2 gives the answer total − 2s.

Where people lose marks

  • Simulating the stone smashing greedily (largest two first), which is not optimal.
  • Searching sums above half the total, which double counts each split.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.