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.
importjava.io.*;importjava.util.*;publicclassSolution{publicstaticvoidmain(String[]args){Scannerin=newScanner(System.in);intn1=in.nextInt();intn2=in.nextInt();intn3=in.nextInt();longtot_1=0L;longtot_2=0L;longtot_3=0L;longmax=0L;// reverse fill the arrays to mimic a stack// also keep a running total for each stackinth1[]=newint[n1];for(intidx=n1-1;idx>=0;idx--){h1[idx]=in.nextInt();tot_1+=(long)h1[idx];}inth2[]=newint[n2];for(intidx=n2-1;idx>=0;idx--){h2[idx]=in.nextInt();tot_2+=(long)h2[idx];}inth3[]=newint[n3];for(intidx=n3-1;idx>=0;idx--){h3[idx]=in.nextInt();tot_3+=(long)h3[idx];}intidx_1=n1-1;intidx_2=n2-1;intidx_3=n3-1;// don't process anything if one of the arrays is empty// since 0 is the default for maxif(n1!=0&&n2!=0&&n3!=0){// use the math principle that if// x > y and y > z then x > z// Remove the highest record until the // stack values are equal across all // three stackswhile(tot_1!=tot_2||tot_1!=tot_3){if(tot_1>tot_2||tot_1>tot_3){tot_1-=(long)h1[idx_1];idx_1--;if(idx_1<0){break;}}if(tot_2>tot_3||tot_2>tot_1){tot_2-=(long)h2[idx_2];idx_2--;if(idx_2<0){break;}}if(tot_3>tot_1||tot_3>tot_2){tot_3-=(long)h3[idx_3];idx_3--;if(idx_3<0){break;}}}if(idx_1>=0&&idx_2>=0&&idx_3>=0){max=tot_1;}}System.out.println(max);}}
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 →
Here is the same code logic using java 7 or 8