Number of Great Partitions - Problem

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 109 + 7.

Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,1], k = 2
Output: 1
💡 Note: Only one great partition: Group A = {1,1} with sum 2, Group B = {2} with sum 2. Both sums ≥ k=2.
Example 2 — Multiple Partitions
$ Input: nums = [3,3,3], k = 4
Output: 0
💡 Note: No great partitions possible. To have both groups with sum ≥ 4, we would need total sum ≥ 8, but with [3,3,3] the maximum one group can have is 6 (two elements) while the other gets 3, which is < 4.
Example 3 — Impossible Case
$ Input: nums = [1,1,1,1], k = 5
Output: 0
💡 Note: Total sum is 4, but we need both groups to have sum ≥ 5. Impossible since 4 < 2×5.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • 1 ≤ nums[i] ≤ 100
  • 1 ≤ k ≤ 109

Visualization

Tap to expand
Number of Great Partitions INPUT Array nums: 1 i=0 2 i=1 1 i=2 Threshold k: k = 2 Possible partitions: Group A | Group B [1,2,1] | [] [1,2] | [1] [2,1] | [1] etc... Total: 2^3 = 8 ways ALGORITHM STEPS 1 Count Invalid Partitions Use DP: sum(group) < k 2 DP Table Setup dp[s] = ways to get sum s sum: 0 1 2 3 4 dp[]: 1 2 2 2 1 invalid = dp[0]+dp[1] = 3 (sums < k=2 are invalid) 3 Calculate Bad Partitions bad = 2 * invalid = 2*3 = 6 (either group sum < k) 4 Subtract from Total great = 2^n - bad great = 8 - 6 - 1 = 1 (handle overlap case) FINAL RESULT Only Valid Partition: Group A 2 sum = 2 >= k Group B 1 1 sum = 2 >= k Output: 1 Both groups have sum >= k = 2 OK Great partition found! Key Insight: Instead of counting valid partitions directly (complex), count INVALID ones using DP! Use complement: Great partitions = Total (2^n) - Bad partitions (where any group sum < k) DP tracks ways to achieve each possible sum. Time: O(n*k), Space: O(k) TutorialsPoint - Number of Great Partitions | DP Approach
Asked in
Google 15 Facebook 12 Amazon 8
12.4K Views
Medium Frequency
~35 min Avg. Time
387 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen