#805
Split Array With Same Average
HardArrayHash TableMathDynamic ProgrammingBit ManipulationBitmaskHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * n/2) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n * n/2)Space O(n)
Instead of checking all combinations, we can use a mathematical property. If the average of two subsets is equal, their sums must be proportional to their sizes. We can use dynamic programming to efficiently find valid subsets.
⚙️
Algorithm
5 steps- 1Step 1: Calculate the total sum and length of the array.
- 2Step 2: Iterate through possible sizes of subset A from 1 to n/2.
- 3Step 3: For each size, check if there exists a subset of that size with a sum that maintains the average condition.
- 4Step 4: Use a dynamic programming approach to track possible sums for each subset size.
- 5Step 5: If a valid subset is found, return true; otherwise, return false.
solution.py13 lines
1def splitArraySameAverage(nums):
2 total_sum = sum(nums)
3 n = len(nums)
4 for size in range(1, n // 2 + 1):
5 if total_sum * size % n == 0:
6 target = total_sum * size // n
7 dp = set([0])
8 for num in nums:
9 for s in list(dp):
10 dp.add(s + num)
11 if target in dp:
12 return True
13 return Falseℹ
Complexity note: The time complexity is O(n * n/2) due to the dynamic programming approach to track possible sums, which is more efficient than the brute force method.
- 1The average condition can be transformed into a sum condition, allowing for more efficient checks.
- 2Dynamic programming can be used to track achievable sums for subsets, reducing the need for exhaustive search.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.