This can be solved easily with binary search on the min-max value.
While solving this in the contest, I wasn't able to come up with this approach. Rather I tried solving the same binary search function "possible" with a different approach and this lead me to a different version of the problem.
Task
Given an array of n positive integers $$$a_{1}$$$,$$$a_{2}$$$,...$$$a_{n}$$$ and an integer $$$m$$$ where $$$m$$$ is a power of 2. Determine the minimum number of numbers to be selected from the array so that their binary $$$OR$$$ will be $$$m-1$$$. If there doesn't exist a solution, output -1.
Input Format
$$$n$$$ $$$m$$$
$$$a_{1}$$$ $$$a_{2}$$$ ... $$$a_{n}$$$
Constraints
$$$1$$$ < $$$n$$$ < $$$10^{5}$$$
$$$1$$$ < $$$m$$$ < $$$2^{10}$$$
$$$0$$$ <= $$$a_{i}$$$ <= $$$m$$$
Sample Input 1
3 32
10 21 31
Sample Output 1
1
Explanation
10 - 0 1 0 1 0
21 - 1 0 1 0 1
31 - 1 1 1 1 1
Selecting 31 will be enough.
Sample Input 2
5 32
9 25 27 10 21
Sample Output 2
2
Explanation
10 - 0 1 0 0 1
21 - 1 1 0 0 1
31 - 1 1 0 1 1
10 - 0 1 0 1 0
21 - 1 0 1 0 1
10 | 21 = 31. So answer will be 2.
I was not able to solve this and also tried searching for the same type of problem on the internet but failed to find one. If anyone has solved this before or has any thoughts of any complexity of the solution, please let me know.
[DELETED as it was wrong solution]
Edit 1: Your output is 3.
Edit 2: Regarding the similarity of the problem, if we know what is the minimum number of numbers we need to get in order to find $$$m-1$$$ i.e. all 1's, then we can use this in the binary search function to calculate the (true, false) for a particular min-max value.
[AGAIN WRONG SOLUTION, maybe I am dumb or problem is way too hard ]
No. I don't think the greedy approach would solve the problem.
Your output is 3.
Then there is a DP solution with O(m) space but TC will be O(n*m) which is not feasible :(
Edit : It may be feasible with $$$ m <= \exp(2,11) $$$ but any further increase in power will not work
Like considering all the subsets but optimizing it with dp?
Yeah we can define DP as
$$$ dp[i] $$$ — minimum number of elements required to have their OR as $$$i$$$
transition would be
Let $$$j$$$ be current OR we are standing at, trying every elements of array
let current element be $$$i$$$
Let $$$x$$$ = $$$j$$$ or $$$arr[i]$$$
$$$ dp[x] = min(dp[x],dp[j]+1) $$$
this would work as even if we OR same index again it will not increase the overall OR
Finally you can print dp[m-1]