To split the array into two non-empty groups with the same average, we need to find a non-empty subset whose sum is proportional to its size, matching the overall average. By scaling the problem to subset sums, we can use dynamic programming and bitmasking to efficiently check all possible subset sizes and sums.
#include<vector>#include<unordered_set>usingnamespace std;
classSolution {
public:bool splitArraySameAverage(vector<int>& nums) {
int n = nums.size(), s =0;
for (int x : nums) s += x;
vector<unordered_set<int>> dp(n+1);
dp[0].insert(0);
for (int x : nums) {
for (int k = n-1; k >=0; --k) {
for (int sum : dp[k]) {
dp[k+1].insert(sum + x);
}
}
}
for (int k =1; k <= n/2; ++k) {
if ((s * k) % n ==0&& dp[k].count(s * k / n)) return true;
}
return false;
}
};
import java.util.*;
classSolution {
publicbooleansplitArraySameAverage(int[] nums) {
int n = nums.length, s = 0;
for (int x : nums) s += x;
Set<Integer>[] dp =new Set[n+1];
for (int i = 0; i <= n; ++i) dp[i]=new HashSet<>();
dp[0].add(0);
for (int x : nums) {
for (int k = n-1; k >= 0; --k) {
for (int sum : dp[k]) {
dp[k+1].add(sum + x);
}
}
}
for (int k = 1; k <= n/2; ++k) {
if ((s * k) % n == 0 && dp[k].contains(s * k / n)) returntrue;
}
returnfalse;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funsplitArraySameAverage(nums: IntArray): Boolean {
val n = nums.size
val s = nums.sum()
val dp = Array(n+1) { mutableSetOf<Int>() }
dp[0].add(0)
for (x in nums) {
for (k in n-1 downTo 0) {
for (sum in dp[k]) {
dp[k+1].add(sum + x)
}
}
}
for (k in1..n/2) {
if ((s * k) % n ==0&& dp[k].contains(s * k / n)) returntrue }
returnfalse }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defsplitArraySameAverage(self, nums: list[int]) -> bool:
n, s = len(nums), sum(nums)
dp = [set() for _ in range(n+1)]
dp[0].add(0)
for x in nums:
for k in range(n-1, -1, -1):
for total in dp[k]:
dp[k+1].add(total + x)
for k in range(1, n//2+1):
if (s * k) % n ==0and (s * k // n) in dp[k]:
returnTruereturnFalse
impl Solution {
pubfnsplit_array_same_average(nums: Vec<i32>) -> bool {
let n = nums.len();
let s: i32= nums.iter().sum();
letmut dp =vec![std::collections::HashSet::new(); n+1];
dp[0].insert(0);
for&x in&nums {
for k in (0..n).rev() {
for&sum in dp[k].iter() {
dp[k+1].insert(sum + x);
}
}
}
for k in1..=n/2 {
if (s * k asi32) % n asi32==0&& dp[k].contains(&(s * k asi32/ n asi32)) {
returntrue;
}
}
false }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution {
splitArraySameAverage(nums: number[]):boolean {
constn=nums.length, s=nums.reduce((a, b) =>a+b, 0);
constdp: Set<number>[] = Array.from({length: n+1}, () =>newSet());
dp[0].add(0);
for (constxofnums) {
for (letk=n-1; k>=0; --k) {
for (constsumofdp[k]) {
dp[k+1].add(sum+x);
}
}
}
for (letk=1; k<=n/2; ++k) {
if ((s*k) %n===0&&dp[k].has(s*k/n)) returntrue;
}
returnfalse;
}
}