[LeetCode] Split Array Into Maximum Number of Subarrays

2871. Split Array Into Maximum Number of Subarrays

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:

  • E**ach 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maxSubarrays(vector<int>& nums) {
long long bit = INT_MAX;
for(auto& n : nums) bit &= n;
long long now = INT_MAX;
if(bit) return 1;
int res = 0;
for(auto& n : nums) {
if(now == bit) {
cout<<n<<endl;
now = INT_MAX;
res += 1;
}
now &= n;
}
if(now == bit) res += 1;
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/01/PS/LeetCode/split-array-into-maximum-number-of-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.