#2518
Number of Great Partitions
HardArrayDynamic ProgrammingDynamic ProgrammingSubset Sum
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * k) |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n * k)Space O(k)
Instead of counting great partitions directly, we count the partitions that do not meet the criteria and subtract from the total possible partitions. This approach leverages dynamic programming to efficiently calculate valid partitions.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the total sum of the array. If total_sum < 2 * k, return 0 as it's impossible to partition.
- 2Step 2: Use dynamic programming to count subsets with sums less than k.
- 3Step 3: Calculate the total number of partitions as 2^n - 1 (excluding the empty set).
- 4Step 4: Subtract the count of invalid partitions from the total partitions to get the number of great partitions.
solution.py23 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countGreatPartitions(nums, k):
5 total_sum = sum(nums)
6 n = len(nums)
7 if total_sum < 2 * k:
8 return 0
9
10 # Count subsets with sum < k
11 dp = [0] * (k)
12 dp[0] = 1
13
14 for num in nums:
15 for j in range(k - 1, num - 1, -1):
16 dp[j] = (dp[j] + dp[j - num]) % MOD
17
18 invalid_count = sum(dp) % MOD
19 total_partitions = pow(2, n, MOD) - 1
20 return (total_partitions - invalid_count + MOD) % MOD
21
22# Example usage
23print(countGreatPartitions([1, 2, 3, 4], 4)) # Output: 6ℹ
Complexity note: The time complexity is O(n * k) because we iterate through each number in the array and update the dp array of size k. This is significantly more efficient than the brute force approach.
- 1If the total sum of the array is less than 2 * k, it's impossible to create great partitions.
- 2Counting invalid partitions can be more efficient than counting valid ones directly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.