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.
#include<stdio.h>#include<stdlib.h>intmain(){longn1;longn2;longn3;longlongtot_1=0;longlongtot_2=0;longlongtot_3=0;scanf("%ld %ld %ld",&n1,&n2,&n3);/* reverse fill array to mimic a stack Also, keep a running total for each array */int*h1=(int*)malloc(sizeof(int)*n1);for(longh1_i=n1-1;h1_i>=0;h1_i--){scanf("%d",&h1[h1_i]);tot_1+=(longlong)h1[h1_i];}int*h2=(int*)malloc(sizeof(int)*n2);for(longh2_i=n2-1;h2_i>=0;h2_i--){scanf("%d",&h2[h2_i]);tot_2+=(longlong)h2[h2_i];}int*h3=(int*)malloc(sizeof(int)*n3);for(longh3_i=n3-1;h3_i>=0;h3_i--){scanf("%d",&h3[h3_i]);tot_3+=(longlong)h3[h3_i];}longlongmax=0L;longidx_1=n1-1L;longidx_2=n2-1L;longidx_3=n3-1L;/* No need to process arrays if one is alredy empty */if(n1!=0&&n2!=0&&n3!=0){/* Remove records from highest stack total until all stack totals are the same */while(tot_1!=tot_2||tot_1!=tot_3){if(tot_1>tot_2&&tot_1>tot_3){tot_1-=(longlong)h1[idx_1];idx_1--;if(idx_1<0){break;}}elseif(tot_2>tot_3){tot_2-=(longlong)h2[idx_2];idx_2--;if(idx_2<0){break;}}else{tot_3-=(longlong)h3[idx_3];idx_3--;if(idx_3<0){break;}}}/* Do a final check to make sure that the stacks are equal. This checks the possibility that stack totals will not be equal without completely depleting one or more stacks */if(idx_1>=0&&idx_2>=0&&idx_3>=0){max=tot_1;}else{max=0L;}}printf("%lld\n",max);/* release array memory */free(h1);free(h2);free(h3);return0;}
I used long long; however, you can get by with just long since the totals don't exceed a billion. I had switched to long long because some of the test cases were erroring out, but it turned out to be a faulty comparison. I had used && instead of || in the while loop.
Equal Stacks
You are viewing a single comment's thread. Return to all comments →
Here is the code in C:
I used long long; however, you can get by with just long since the totals don't exceed a billion. I had switched to long long because some of the test cases were erroring out, but it turned out to be a faulty comparison. I had used && instead of || in the while loop.