oneby7

2-D Dynamic Programming Bitmask DP

598. Partition to K Equal Sum Subsets

Medium

You are given an array of positive integers nums and an integer k. Split the array into exactly k groups so that every element goes into exactly one group. A group can hold any elements of the array, in any order, and the groups do not have to be the same size.

Return true if some split gives all k groups the same sum, and false otherwise.

Example 1

Input: nums = [6, 1, 4, 3, 5, 2, 3], k = 3

Output: true

Explanation: The total is 24, so each group needs 8. The groups [6, 2], [5, 3] and [4, 1, 3] all sum to 8.

Example 2

Input: nums = [5, 5, 5, 3], k = 2

Output: false

Explanation: Each group needs 9. A 5 and the 3 make only 8, and two 5s make 10, so no group can sum to 9.

Example 3

Input: nums = [1000000000, 1000000000, 1000000000], k = 3

Output: true

Explanation: Each element forms a group of its own, and every group sums to 109.

Check your understanding

Work out the answer for this input before you write any code.

nums = [5, 4, 3, 3, 3, 2], k = 2

Constraints

  • 1 ≤ nums.length ≤ 20
  • 1 ≤ nums[i] ≤ 109
  • 1 ≤ k ≤ nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.