805. Split Array With Same Average
Description
You are given an integer array nums
.
You should move each element of nums
into one of the two arrays A
and B
such that A
and B
are non-empty, and average(A) == average(B)
.
Return true
if it is possible to achieve that and false
otherwise.
Note that for an array arr
, average(arr)
is the sum of all the elements of arr
over the length of arr
.
Example 1:
Input: nums = [1,2,3,4,5,6,7,8] Output: true Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have an average of 4.5.
Example 2:
Input: nums = [3,1] Output: false
Constraints:
1 <= nums.length <= 30
0 <= nums[i] <= 104
Solutions
Solution: Dynamic Programming
- Time complexity: O(n2*2n)
- Space complexity: O(n*2n)
JavaScript
js
/**
* @param {number[]} nums
* @return {boolean}
*/
const splitArraySameAverage = function (nums) {
const n = nums.length;
const sum = nums.reduce((result, num) => result + num);
/*
sum / n === sum1 / count1 === sum2 / (n - count1)
=> sum1 = sum * count1 / n
=> sum * count1 % n === 0
**/
const sums = new Array(n)
.fill('')
.map(_ => new Set());
sums[0].add(0);
for (const num of nums) {
for (let count = n - 1; count > 0; count--) {
const target = (sum * count) / n;
for (const previous of sums[count - 1]) {
const current = previous + num;
sums[count].add(current);
if ((sum * count) % n !== 0) continue;
if (current === target) return true;
}
}
}
return false;
};