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
Split Array Into Maximum Number of Subarrays INPUT nums array: 1 i=0 0 i=1 2 i=2 0 i=3 1 i=4 Binary representation: 1 = 001 0 = 000 2 = 010 0 = 000 1 = 001 Goal: Split into maximum subarrays with min sum of AND scores ALGORITHM STEPS 1 Initialize current_and = -1 (all 1s) count = 1 2 Iterate array AND each element with current running AND 3 Check for Zero If AND becomes 0: count++, reset AND 4 Return count Max splits found Trace: 1 AND 1 = 1 1 AND 0 = 0 [Split!] Reset: 2 2 AND 0 = 0 [Split!] Reset: 1 End [Split!] FINAL RESULT 4 Subarrays with AND score = 0: Subarray 1: [1, 0] --> 1 AND 0 = 0 Subarray 2: [2, 0] --> 2 AND 0 = 0 Subarray 3: [1] --> score = 1 Subarray 4: Output: 4 Maximum Subarrays [OK] Sum of scores = 0 (minimum possible) Key Insight: The minimum possible sum of AND scores is 0 (since AND of full array can reach 0). We greedily split whenever current AND becomes 0, as this contributes 0 to the sum and maximizes the number of splits. If total AND is not 0, we can only have 1 subarray. TutorialsPoint - Split Array Into Maximum Number of Subarrays | Greedy - Split When AND Becomes 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