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.
Key facts to realize to achieve the required runtime:
any stack that is higher than any other can have a cylinder removed in the next step
removing cylinders from the stack tops, we return on the first instance of finding (all three) equal height cylinders.
I chose not to actually remove cylinders from the lists/stacks (which is possibly an expensive operation) but instead to maintain an index, per stack, of the top cylinder. But maybe list element removal would have worked too.
Java below:
publicstaticintCylHeight(List<Integer>h1){intheight=0;for(intc:h1){height+=c;}returnheight;}publicstaticbooleanCheckEqualSizes(inth1Size,inth2Size,inth3Size){if(h1Size==h2Size&&h2Size==h3Size)returntrue;returnfalse;}publicstaticintChooseNext(inth1Size,inth2Size,inth3Size){if(h1Size>h2Size){return1;}else{if(h2Size>h3Size){return2;}}return3;}publicstaticintequalStacks(List<Integer>h1,List<Integer>h2,List<Integer>h3){/* choose the first stack that is higher than any other and then remove a cylnder stop on the first instance of equal stack heights */inth1Size=CylHeight(h1);inth2Size=CylHeight(h2);inth3Size=CylHeight(h3);intmyCyl1=0;intmyCyl2=0;intmyCyl3=0;intwhichStack;while(true){if(CheckEqualSizes(h1Size,h2Size,h3Size)){returnh1Size;}whichStack=ChooseNext(h1Size,h2Size,h3Size);switch(whichStack){case1:h1Size-=h1.get(myCyl1++);break;case2:h2Size-=h2.get(myCyl2++);break;case3:h3Size-=h3.get(myCyl3++);break;}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Equal Stacks
You are viewing a single comment's thread. Return to all comments →
Key facts to realize to achieve the required runtime:
Java below: