ONLINE ASSESSMENT
Anonymous User
923

Question: MAX OR SUBARRAY
You are given an array A of size N. Now, consider all the subarrays starting at index i - [Ai],[Ai,Ai+1],...,[Ai,...,An]. The score of a subarray is defined as the value obtained after taking the bitwise OR of every element of that subarray. You call a subarray good if the score of that subarray is maximum among all subarrays starting at index i. For every index i, determine the length of the smallest good subarray.

Given an array A, for every index i, determine the smallest subarray starting at i whose bitwise OR of elements is maximum among all subarrays starting at that index.

Note: A subarray is a sequence of consecutive elements of an array.

Example-1

N = 3
A = [1, 2, 3]
Approach

For i = 1, and size of subarray = 1, score of this subarray is 1. For size = 2, the score is 1|2=3 and for size = 3, the score is 1|2|3=3. You can see that the maximum score is 3, and the smallest size of the subarray starts at 1, which gives this maximum score 2. So answer for 1st index = 2.
For i = 2 and size = 1, the score is 2 and for size = 2, the score is 2|3=3, so answer for i=2 is 2.
For i = 3 and size = 1, the score is 3. So the answer for i = 3 is 1.
Answer: [2, 2, 1]

Example-2:
Given,
N = 3
A = [3, 1, 2]
Approach

For i = 1, subarray of size = 1 will give bitwise OR = 3. This is the maximum value that we can get.
For i = 2, subarray of size = 2 will give bitwise OR = 3.
For i = 3, you can only take size = 1, and bitwise OR will be 2.
Hence the answer is [1, 2, 1].

Example-3:
Given,
N = 3
A = [2, 3, 2]
Approach

For i = 1 and size = 2, value of bitwise OR will be 3. This is the maximum value that we can get.
For i = 2 and size = 1, value of bitwise OR will be 3.
For i = 3 and size = 1, value of bitwise OR will be 2.
Hence the answer is [2, 1, 1].

Comments (5)