I came across this question in a programming contest:
We are given an array consisting of n elements. At each iteration, you can select any two elements ai and aj and replace ai with ai & aj. & is the bitwise AND operator. Find the minimum number of AND operations needed to make all array elements zero.
Suppose that there is a solution for the given inputs. What is the optimal solution for this problem?
Edit: I've added my DP solution for the problem which takes more than 1 second to run. Any suggestion for speeding it up?
0 < n < 65535
D: maximum number of digits in base 2 (0 < D < 17)
GOAL: 2^D - 1
T[i][X] => minimum number of elements from {n_0, n_1, ..., n_i} that make X zero
T[i][0] = 0
T[0][X>0] = INF
T[i][X] = min( 1 + T[i-1][X & n_i] , T[i-1][X] )
T[n][GOAL] -> min number of AND operations
{1,1}
there is no solution because1 & 1 = 1
, so the array cannot be cleared with the described operations. – Soule