805. Split Array With Same Average

📋 Đề Bài

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

🧠 Thuật Toán & Kỹ Thuật

Hash Table (Bảng băm)Bit Manipulation (Thao tác bit)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

C++ 0805-split-array-with-same-average.cpp
class Solution {
public:
    unordered_map<int, unordered_set<double>> masking(vector<int> nums) {
        int n = nums.size();
        int m = (1 << n);
        
        unordered_map<int, unordered_set<double>> ans;
        
        for (int mask = 0; mask < m; ++mask) {
            int sum = 0, len = 0;
            for (int i = 0; i < n; ++i) {
                if (mask & (1 << i)) {
                    len++;
                    sum += nums[i];
                }
            }
            ans[len].insert(sum);
        }
        
        return ans;
    }
    
    bool splitArraySameAverage(vector<int>& nums) {
        int n = nums.size();
        int m = n >> 1;
        vector<int> nums1(nums.begin(), nums.begin() + m);
        vector<int> nums2(nums.begin() + m, nums.end());
        unordered_map<int, unordered_set<double>> allSubset1 = masking(nums1);
        unordered_map<int, unordered_set<double>> allSubset2 = masking(nums2);
        
        int sz1 = nums1.size();
        int sz2 = nums2.size();
        
        double sum = accumulate(nums.begin(), nums.end(), 0);
        
        for (int len1 = 0; len1 <= sz1; ++len1) {
            for (double sum1 : allSubset1[len1]) {
                for (int len2 = 0; len2 <= sz2; ++len2) {
                    if (len1 + len2 == 0 or len1 + len2 == n) {
                        continue;
                    }
                    
                    double sum2 = (sum * (len1 + len2)) / n - sum1; 
                    
                    if (allSubset2[len2].count(sum2)) {
                        return true;
                    }
                }
            }
        }
        
        return false;
    }
};