Split Array Into Maximum Number of Subarrays — LeetCode 2871 Python Solution
MediumGreedyBit ManipulationArray
- Problem
- #2871
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array nums consisting of non-negative integers. We define the score of subarray nums[l..r] such that l <= r as nums[l] AND nums[l + 1] AND ...
Example
- Input
- nums = [1,0,2,0,1,2]
- Output
- 3
- Explanation
- We can split the array into the following subarrays:
Python solution
Python
class Solution:
def maxSubarrays(self, nums: List[int]) -> int:
score, ans = -1, 1
for num in nums:
score &= num
if score == 0:
score = -1
ans += 1
return 1 if ans == 1 else ans - 1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2871. Split Array Into Maximum Number of Subarrays is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2871. Split Array Into Maximum Number of Subarrays?
- LeetCode 2871. Split Array Into Maximum Number of Subarrays is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2871. Split Array Into Maximum Number of Subarrays?
- The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 2871. Split Array Into Maximum Number of Subarrays?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2871. Split Array Into Maximum Number of Subarrays cover?
- LeetCode 2871. Split Array Into Maximum Number of Subarrays is tagged Greedy, Bit Manipulation and Array on LeetCode.