Sherlock and MiniMax Discussions | Algorithms | HackerRank
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.
Counting everything is slow: 3 test cases will fail.
Focus the distance between the list elements!
publicstaticintsherlockAndMinimax(List<Integer>arr,intp,intq){//I need a sorted set, and in this sorted set: higher() and lower() functions are very usefulTreeSet<Integer>tree=newTreeSet<Integer>(arr);//If p is upper bound or q is lower bound we are ready, so I made cases: intoutput=0;if(q<=tree.first()){output=tree.first();}elseif(p>=tree.last()){output=tree.last();/*here: we have element(s) between p and q these elements generates intervals; I need the widest interval, so I compare them but be careful, we have to add one new interval before the first one end one after the least one*/}else{intstart=0;intend=0;if(tree.contains(p)||tree.higher(p)==null){start=p;//this is the start of the added new "before" interval:}else{start=2*p-tree.higher(p);}if(tree.contains(q)||tree.lower(q)==null){end=q;}else{//this is the end of the added new "after" interval:end=2*q-tree.lower(q);}inti=start;//width:intmaxDiff=0;//center of the actual best interval:intmiddle=0;tree.add(end);while(i<=end){if(tree.higher(i)!=null){intactDiff=(tree.higher(i)-i)/2;//comparison of the widths:if(actDiff>maxDiff&&(tree.higher(i)+i)/2<=q){maxDiff=actDiff;middle=(tree.higher(i)+i)/2;}i=tree.higher(i);}else{break;}}output=middle;}returnoutput;}
Sherlock and MiniMax
You are viewing a single comment's thread. Return to all comments →
Counting everything is slow: 3 test cases will fail. Focus the distance between the list elements!