#2871
Split Array Into Maximum Number of Subarrays
MediumArrayGreedyBit ManipulationBit ManipulationGreedy
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution focuses on the properties of the bitwise AND operation. If the overall AND of the array is 0, we can split it into multiple subarrays. If not, we can only have one subarray. This drastically reduces the complexity.
⚙️
Algorithm
4 steps- 1Step 1: Calculate the overall AND of the entire array.
- 2Step 2: If the overall AND is 0, iterate through the array to count how many times we encounter a 0, which indicates a potential split point.
- 3Step 3: Return the count of splits plus one (for the last subarray).
- 4Step 4: If the overall AND is not 0, return 1 as we can only have one subarray.
solution.py7 lines
1def maxSubarrays(nums):
2 overall_and = nums[0]
3 for num in nums:
4 overall_and &= num
5 if overall_and == 0:
6 return nums.count(0) + 1
7 return 1ℹ
Complexity note: The time complexity is O(n) because we only need to traverse the array a couple of times. The space complexity is O(1) since we are using a constant amount of extra space.
- 1The overall AND of the array determines the possibility of splitting.
- 2A score of 0 allows for maximum splits.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.