Problem Description
Given an array nums of non-negative integers, split it into one or more contiguous subarrays so that every element is in exactly one subarray. Define the score of a subarray as the bitwise AND of all of its elements. The objective is to minimize the total score (i.e. the sum of the scores of the subarrays) while maximizing the number of subarrays in the split. Return the maximum number of subarrays that can be formed under this condition.
Key Insights
- The minimal possible score overall is the bitwise AND of the entire array.
- For any split to achieve the minimum sum, each subarray must have a bitwise AND equal to the global AND.
- A greedy approach is viable: iterate over the array, maintaining a running AND; whenever the running AND equals the global AND, a valid subarray is complete.
- Reset the running AND and continue to form the next valid subarray.
- This method naturally maximizes the number of subarrays.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the array (each element is processed once). Space Complexity: O(1), constant extra space is used.
Solution
First, compute the global AND of the entire array. This value is the lower bound for the total sum, since any valid split must have each subarray's AND equal to at least this value. Then, iterate through the arraymaintaining a running AND of the current subarray. When the running AND becomes equal to the global AND, a valid subarray is identified; increment your count and reset the running AND for the next segment. Continue this until the end of the array. The count will be the maximum number of subarrays achieving the minimal sum, as each split is as short as possible while still satisfying the condition.