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.
Got AC with Scanner. Shouldn't be too difficult as the optimal algorithm is O(n + m):
intcount=0;finalStack<Long>leftStack=newStack<>();for(inti=0;i<sums1.length&&sums1[i]<=x;++i){++count;leftStack.push(sums1[i]);}intmax=count;for(intj=0;j<sums2.length&&sums2[j]<=x;++j){// check whether or not you can add the next sum from // right stack (sums2) to the current top of left stackif(!leftStack.isEmpty()&&sums2[j]+leftStack.peek()>x){// count was increasing but now we have to pop off// stack before adding next element in sums2, // check count now (because it's about to // decrease from removing from the left stack)if(count>max)max=count;// keep popping off the stack until the left sum// and the right sum are <= x OR we've emptied // the left stackwhile(!leftStack.isEmpty()&&sums2[j]+leftStack.peek()>x){--count;leftStack.pop();}}// we just added from the right stack, so increment++count;}if(count>max)max=count;
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Game of Two Stacks
You are viewing a single comment's thread. Return to all comments →
Got AC with Scanner. Shouldn't be too difficult as the optimal algorithm is O(n + m):