Split Array Into Maximum Number of Subarrays - 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 ... AND nums[r] where AND is the bitwise AND operation.

Consider splitting the array into one or more subarrays such that the following conditions are satisfied:

  • Each element of the array belongs to exactly one subarray.
  • The sum of scores of the subarrays is the minimum possible.

Return the maximum number of subarrays in a split that satisfies the conditions above.

A subarray is a contiguous part of an array.

Input & Output

Example 1 — Basic Split
$ Input: nums = [1,0,2,0,1]
Output: 4
💡 Note: We can split into [1], [0], [2,0], [1]. Scores are 1, 0, 0, 1 with sum = 2. This is minimum possible, and we have 4 subarrays.
Example 2 — Single Subarray
$ Input: nums = [5,7,1,3]
Output: 1
💡 Note: The entire array AND is 5&7&1&3 = 1 > 0. To minimize sum, we must keep as one subarray [5,7,1,3] with score 1.
Example 3 — All Zeros
$ Input: nums = [0,0,0]
Output: 3
💡 Note: We can split into [0], [0], [0]. Each subarray has score 0, sum = 0 (minimum), with 3 subarrays maximum.

Constraints

  • 1 ≤ nums.length ≤ 104
  • 0 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Split Array Into Maximum Subarrays: [1,0,2,0,1]10201Original Array[1][0][2,0][1]Result: 4 subarrays with minimum sum = 2
Understanding the Visualization
1
Input
Array [1,0,2,0,1] needs to be split optimally
2
Process
Find minimum sum, then split greedily
3
Output
Maximum 4 subarrays with minimum sum
Key Takeaway
🎯 Key Insight: AND operations only decrease values, so split greedily when reaching zero
Asked in
Google 12 Amazon 8 Microsoft 6
8.5K Views
Medium Frequency
~25 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen