#2518
Hard Algorithms Number of great partitions
Array Dynamic Programming
33.4% acceptance
Feb 25, 2026
490
12
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn count_partitions(nums: Vec<i32>, k: i32) -> i32 {
const MOD: u64 = 1_000_000_007;
let k = k as i64;
let n = nums.len();
let total: i64 = nums.iter().map(|&x| x as i64).sum();
if total < 2 * k {
return 0;
}
// Count subsets with sum < k (0/1 knapsack, only include elements < k)
let target = k as usize;
let mut dp = vec![0u64; target];
dp[0] = 1;
for &num in &nums {
if (num as i64) < k {
let num = num as usize;
for j in (num..target).rev() {
dp[j] = (dp[j] + dp[j - num]) % MOD;
}
}
}
let bad: u64 = dp.iter().sum::<u64>() % MOD;
// Total = 2^n
let mut total_pow = 1u64;
for _ in 0..n {
total_pow = total_pow * 2 % MOD;
}
((total_pow + MOD * 2 - 2 * bad % MOD) % MOD) as i32
}
}