aboutsummaryrefslogtreecommitdiff
path: root/long_nice_subarr.c
blob: cfa50f38fc9bf87ef479736ab165ea500144cea3 (plain)
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
50
51
52
53
// 2401. Longest Nice Subarray
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * given an array 'nums' consisting of positive integers. we call a subarray of
 * 'nums' nice if the bitwise AND of every pair of elements that are in
 * different positions in the subarray is equal to 0. return the length of the
 * longest nice subarray. a subarray is contiguous part of an array. note that
 * subarrays of length 1 are always considered nice.
 */

bool check(int *bit, int n) {
  for (int i = 0; i < n; i++)
    if (bit[i] > 1)
      return false;
  return true;
}

int longestNiceSubarray(int *nums, int nums_size) {
  int *bit = calloc(32, sizeof(int));
  int left = 0, right = 0;
  while (right < nums_size) {
    int k = nums[right], pos = 0;
    while (k) {
      if (k % 2 == 1)
        bit[pos]++;
      k /= 2;
      pos++;
    }
    right++;
    if (!check(bit, 32)) {
      k = nums[left];
      pos = 0;
      while (k) {
        if (k % 2 == 1)
          bit[pos]--;
        k /= 2;
        pos++;
      }
      left++;
    }
  }
  return right - left;
}

int main() {
  int n1[] = {1, 3, 8, 48, 10}, ns1 = 5;
  int n2[] = {3, 1, 5, 11, 13}, ns2 = 5;
  printf("%d\n", longestNiceSubarray(n1, ns1)); // expect: 3
  printf("%d\n", longestNiceSubarray(n2, ns2)); // expect: 1
}