Number of Great Partitions Problem
Description
LeetCode Problem 2518.
You are given an array nums consisting of positive integers and an integer k.
Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k.
Return the number of distinct great partitions. Since the answer may be too large, return it modulo 10^9 + 7.
Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.
Example 1:
Input: nums = [1,2,3,4], k = 4
Output: 6
Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]).
Example 2:
Input: nums = [3,3,3], k = 4
Output: 0
Explanation: There are no great partitions for this array.
Example 3:
Input: nums = [6,6], k = 2
Output: 2
Explanation: We can either put nums[0] in the first partition or in the second partition.
The great partitions will be ([6], [6]) and ([6], [6]).
Constraints:
1 <= nums.length, k <= 10001 <= nums[i] <= 10^9
Solution
Approach: Count Bad Partitions with Knapsack
There are 2^n ways to split the numbers into two ordered groups. If the total is less than 2k, no split can give both groups sum at least k, so the answer is 0.
Otherwise subtract the bad splits, those where one group has sum below k. Count the subsets with sum below k using a 0-1 knapsack DP f[i][j] (ways to pick from the first i numbers with sum j). The small group can be either of the two, so the number of bad splits is twice the sum of f[n][j] over j < k. All arithmetic is modulo 10^9 + 7.
Complexity: O(n * k) time and space.
class Solution:
def countPartitions(self, nums: List[int], k: int) -> int:
if sum(nums) < k * 2:
return 0
mod = 10**9 + 7
n = len(nums)
f = [[0] * k for _ in range(n + 1)]
f[0][0] = 1
ans = 1
for i in range(1, n + 1):
ans = ans * 2 % mod
for j in range(k):
f[i][j] = f[i - 1][j]
if j >= nums[i - 1]:
f[i][j] = (f[i][j] + f[i - 1][j - nums[i - 1]]) % mod
return (ans - sum(f[-1]) * 2 + mod) % mod