I am not able to solve this.please help
Hacker rank AND xor OR
The idea is that if you have a value b in your stack, and you encounter a value c which is smaller, then b cannot form a minimum pair with anything to the right of c. So once you yield the pair (b,c) you can safely dispose of b (you already handled possible pairs to the left).
-> For e.g. A=[4,5,3,7] yields => (i,top): (5,4);(3,5);(3,4);(7,3), which are the only contiguous pairs of two smallest elements. Note, for example, (4,7) is impossible, because that includes all of A => (3,4). [see below] New smaller elements pop out earlier (contiguously) elements, such as 3 popping 5 and 4.
-> Loop through A linearly.
-> When to push and pop to the stack? Push to the stack each new element in A, i, and if i is smaller than stack top, keep popping until all bigger earlier values popped (or stack empty) before adding i. This way any new smaller element pops all previous bigger elements, and the stack keeps pushing new elements when empty - always having a new pair (at least one element in non-empty stack and new element i).
simplify the boolean function (^ is for XOR):
(((A B) ^ (A + B)) (A ^ B)) =
apply A ^ B = (A'B) + (A B')
( ((A B)' (A + B)) + ((A B) (A + B)')) (A ^ B)) =
apply DeMorgan law (X+Y+...)'=X'Y'Z'... and (XYZ...)'=X'+Y'+...
( ((A' + B') (A + B)) + ((A B) (A' B'))) (A ^ B)) =
apply Distributive Law X(Y+Z) = XY + XZ
(A'A + A'B + AB' + BB' + AA' + BB') (A ^ B) =
apply X+X=X, XX=X
(A'B + AB') (A ^ B) =
(A ^ B) (A ^ B) = A ^ B = A xor B
Solution :
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
int main()
{ vector <long int> v;
stack <long int> s;
long int temp,i,n;
long long max_xor=0,min_xor;
cin>>n;
for(i=0;i<n;i++)
{
cin>>temp;
v.push_back(temp);
}
for(i=0;i<n;i++)
{
while(!s.empty())
{
min_xor=v[i]^s.top();
if(min_xor>max_xor)
max_xor=min_xor;
if(v[i]<s.top())
s.pop();
else
break;
}
s.push(v[i]);
}
cout<<max_xor<<endl;
}
You want to generate the subset from array [1,3,5,7,8] cause subset won’t be required to solve this question.
No,my question is not related to this .It was related to some other question w
my question is bascically to find all subsets of size 2 in an array
For the mentioned array, answer would be
1 3
1 5
1 7
1 8
3 5
3 7
3 8
5 7
5 8
7 8
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.