Input: nums =[1,0,2,0,1,2]Output: 3Explanation: We can split the array into the following subarrays:-[1,0]. The score of this subarray is1 AND 0=0.-[2,0]. The score of this subarray is2 AND 0=0.-[1,2]. The score of this subarray is1 AND 2=0.The sum of scores is0+0+0=0, which is the minimum possible score that we can obtain.It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return3.
Input: nums =[5,7,1,3]Output: 1Explanation: We can split the array into one subarray:[5,7,1,3]with a score of 1, which is the minimum possible score that we can obtain.It can be shown that we cannot split the array into more than 1 subarray with a total score of 1. So we return1.
To minimize the sum of subarray scores, we want as many subarrays as possible with a score of 0. This happens whenever the running AND becomes zero, so we greedily start a new subarray each time this occurs.
classSolution {
public:int maxSubarrays(vector<int>& nums) {
int ans =0, cur =-1;
for (int x : nums) {
cur &= x;
if (cur ==0) {
++ans;
cur =-1;
}
}
returnmax(ans, 1);
}
};
classSolution {
publicintmaxSubarrays(int[] nums) {
int ans = 0, cur =-1;
for (int x : nums) {
cur &= x;
if (cur == 0) {
++ans;
cur =-1;
}
}
return Math.max(ans, 1);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funmaxSubarrays(nums: IntArray): Int {
var ans = 0var cur = -1for (x in nums) {
cur = cur and x
if (cur ==0) {
ans++ cur = -1 }
}
return maxOf(ans, 1)
}
}
1
2
3
4
5
6
7
8
defmaxSubarrays(nums: list[int]) -> int:
ans, cur =0, -1for x in nums:
cur &= x
if cur ==0:
ans +=1 cur =-1return max(ans, 1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfnmax_subarrays(nums: Vec<i32>) -> i32 {
letmut ans =0;
letmut cur =-1;
for x in nums {
cur &= x;
if cur ==0 {
ans +=1;
cur =-1;
}
}
ans.max(1)
}
}