1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class Solution { public int maxSubarrays(int[] nums) { int n = nums.length;
int cnt0 = 0, cur = nums[0]; boolean flag = false; for (int x : nums) { if (flag) { cur = x; flag = false; } else cur &= x; if (cur == 0) { ++cnt0; flag = true; } } int l = cnt0, r = n; int target = nums[0]; for (int x : nums) target &= x; while (l <= r) { int mid = (l + r) >> 1; if (check(nums, mid, target)) l = mid + 1; else r = mid - 1; } return r; }
private boolean check(int[] nums, int k, int target) { int sum = 0, cur = nums[0], cnt = 0, n = nums.length; for (int i = 0; i < n; ++i) { int x = nums[i]; cur &= x; if (cur <= target && sum + cur <= target) { ++cnt; sum += cur; if (i == n - 1) break; cur = nums[i + 1]; } } return cnt >= k && sum == target; } }
|