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 modulo109 + 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]).
Suppose we partitioned our array into subsets s1 and s2 :-
Final subsets -> s1 and s2
condition to be satisfied : s1 >= k and s2 >= k
s1+s2 >= 2*k
s1+s2 = sum of array = s
so sum of array i.e s must be >= 2*k
Converse of the above condition : s1>=k and s2>=k
is :
(1) s1<k and s2<k
(2) s1<k and s2>=k
(3) s1>=k and s2<k
if(sum < 2 * k) {
return 0;
}
will eliminate (1), and (2) (3) 是對稱的,所以只需要計算 (2)(或 (3))。
Final ans= 2^n - count in (2) - count in (3)
= 2^n - 2*(count in (2)) [as count in (2) = count in (3)]
DP - 2D knapsack
Time Complexity: O(nk), Space Complexity: O(nk)
注意 total = (total % mod + mod) % mod; ,因為有取 mod,所以在 total -= 2*ways; 之後值有可能是負的。就像是在計算 -3 mod 7 時,要先做 -3 + 7 = 4,再做 4 % 7 = 4。( % 代表除法取餘數)