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:
3
💡 Note:
We can split into [1,0], [2,0], [1]. Scores are 0, 0, 1 with sum = 1. But to get minimum sum = 0, we split as [1,0,2,0], [1] with scores 0, 1, sum = 1. Actually, the minimum sum is achieved by maximally splitting where each part has AND = 0: [1,0], [2,0], [1] giving 3 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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code