Bitwise ORs of Subarrays
We have an array A of non-negative integers.
For every (contiguous) subarray B = [A[i], A[i+1], …, A[j]] (with i <= j), we take the bitwise OR of all the elements in B, obtaining a result A[i] | A[i+1] | … | A[j].
Return the number of possible results. (Results that occur more than once are only counted once in the final answer.)
Example
Input: [1,1,2]
Output: 3
Explanation:
The possible subarrays are [1], [1], [2], [1, 1], [1, 2], [1, 1, 2].
These yield the results 1, 1, 2, 1, 3, 3.
There are 3 unique values, so the answer is 3.
Solution
func subarrayBitwiseORs(A []int) int {
var cur,cur2 []int
ret:= make(map[int]bool, len(A))
for _,i := range A{
isInCur2 := make(map[int]bool, len(cur))
cur2 = append(cur2, i)
ret[i], isInCur2[i] = true, true
for _,j :=range cur{
j |= i
if !isInCur2[j]{
cur2 = append(cur2, j)
ret[j], isInCur2[j] = true, true
}
}
cur, cur2 = cur2, cur[:0]
}
return len(ret)
}