We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
If we use binary tree to store the numbers as we go left to right and right to left correspondingly and we insert the new value at the top of the tree, we can check its closest bigger neighbour in its first right child, (if there is one).
Then the solution is as easy as:
// read input in vector a;node*treapL=nullptr,*treapR=nullptr;for(inti=0,j=n-1;i<n;i++,j--){node::insert(newnode(a[i],i+1),treapL);node::insert(newnode(a[j],j+1),treapR);l[i]=treapL->right?treapL->right->i:0;// 0 if no right childr[j]=treapR->right?treapR->right->i:0;}for(inti=0;i<n;i++)ans=max(ans,(int64_t)l[i]*r[i]);cout<<ans<<'\n';
Now how do we implement the treap? We just need binary search tree which stores value and index
structnode{intv,i;// value and indexnode*left,*right;node(intx,intindex){v=x;i=index;}staticvoidinsert(node*x,node*&t){if(!t)t=x;elseif(t->v==x->v)t->i=x->i;elsesplit(t,x->left,x->right,x->v),t=x;}staticvoidsplit(node*p,node*&l,node*&r,intval){if(!p)l=r=p;elseif(p->v>val)split(p->left,l,p->left,val),r=p;elsesplit(p->right,p->right,r,val),l=p;}};
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Find Maximum Index Product
You are viewing a single comment's thread. Return to all comments →
Interesting solution with treе
30 lines of code, O(nlogn), C++, 100%
If we use binary tree to store the numbers as we go left to right and right to left correspondingly and we insert the new value at the top of the tree, we can check its closest bigger neighbour in its first right child, (if there is one). Then the solution is as easy as:
Now how do we implement the treap? We just need binary search tree which stores value and index