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<bits/stdc++.h>usingnamespacestd;intmain(){intg;cin>>g;for(inta0=0;a0<g;a0++){intn;intm;intx;cin>>n>>m>>x;vector<int>a(n);for(inta_i=0;a_i<n;a_i++){cin>>a[a_i];}vector<int>b(m);for(intb_i=0;b_i<m;b_i++){cin>>b[b_i];}intsum=0,count=0,temp=0,i=0,j=0;while(i<n&&sum+a[i]<=x){//considering only first stack and calculating countsum+=a[i];i++;}count=i;while(j<m&&i>=0){//now adding one element of second stack at a time and subtracting the top element of first stack and calculating the count sum+=b[j];j++;while(sum>x&&i>0){i--;sum-=a[i];}if(sum<=x&&i+j>count)count=i+j;}cout<<count<<endl;}return0;}
first I'm only considering one stack and calculating the sum and count number.Then I'm adding one element from second stack at a time to the calculated sum and comparing it with required sum.If the calculated sum is greater we subract the last added element of first stack from sum.
It just restricts extra passes, since when i<0 you know that in the sum there are only numbers of second stack, you have already subtracted all the numbers of first stack. And now no need to continue.
I agree with @farhan_tanvir_u1, the way you have it coded. The second stack will be checked to the end, once the first stack has been totally depleted, and the second stack holds all the numbers, it will not stop.
Suggest adding an additional check for sum <= x. Once i = 0 && sum > x, you can stop checking the second stack.
yes that condition is unnecessary because i will never be negative because of the (i>0) check in inner while loop. The code can be modified to save few iterations by introducing a check
if(sum>x)
break;
after the inner while loop.
i was still confused after reading this but my realization below helped clarify; so for those who still may be confused:
the whole idea of adding the recently popped 2nd stack element to the sum and removing the last 1st stack element if the sum is greater than the sum limit is to maintain the max count thus far.
therefore, the max count will never decrease and will only increase if either 1) we can add an element from the 2nd stack without removing from the sum or 2) removing an "added element from 1st stack" allows for 2 or more additional elements from 2nd stack.
publicstaticinttwoStacks(intmaxSum,List<Integer>a,List<Integer>b){// Write your code hereStack<Integer>st1=newStack<>();Stack<Integer>st2=newStack<>();for(inti=0;i<a.size();i++){st1.push(a.get(i));}for(inti=0;i<b.size();i++){st2.push(b.get(i));}intlengthB=0;intsum=0;while(lengthB<b.size()&&(sum+b.get(lengthB))<=maxSum){sum+=b.get(lengthB);lengthB++;}intmaxScore=lengthB;for(inti=0;i<a.size();i++){sum+=a.get(i);while(sum>maxSum&&lengthB>0){lengthB--;sum-=b.get(lengthB);}if(sum>maxSum){break;}maxScore=Math.max(maxScore,lengthB+i+1);}returnmaxScore;}
what's the logic of decrementing lengthB first and then subrtracting the it from sum instead why can't we subtract it first and then decrement the index.
Hey! I was recently looking for something new in online games and came across Aviator. The game is pretty engaging and feels fair, which really caught my attention.
I found a clear explanation of how its fairness system works on https://aviator-games.co.za/provably-fair-aviator/ — worth a read if you're curious about how these mechanics are set up.
Online club are acquiring fans, whenever contrasted with exemplary betting clubs. These days, players have the amazing chance to remain in an agreeable climate at home, and simultaneously take an interest in the round of roulette, finding a seat at a virtual web-based table. Assuming you are another player to the web-based roulette game and need to find success, you want to get to know the 7 fundamental standards of the game and, obviously, stick to them. There are 7 best ways to play live dealer roulette that each client should follow.It is fundamental for every player to draw an individual line for themselves. The initial and most significant stage before inundation into the universe of online gambling clubs is to contemplate and decide your bankroll plainly. Prior to beginning the game, decide how much cash you will spend in a web-based gambling club. Additionally, a web-based club can offer the assistance of a store limit, a bet breaking point, and, surprisingly, a cutoff on the span of the game.To pick a decent web-based club, ensure that it likewise has a permit to work from one of the authorized betting networks: UK Gambling Committee, Curacao Licensed Committee, Malta Gambling Committee, Gibraltar Gambling License, Supervisory Gambling Commission. Furthermore, prior to joining an internet based club, every player ought to look into the terms of collaboration. The player ought to peruse and grasp the standards of the club, as they can be totally disparate in each web-based club, and have similar significance as the license.Despite the gigantic choice of live dealer roulette, most players have their number one virtual table, which they would rather not change. In the event that you actually haven't observed the club name that suits you best, just relax. There is a finished top rundown of live gambling club games accessible on such world class assets as PlayTech, Pragmatic Play, Evolution Gaming. Each game has its own guidelines, and as you foster your playability, you can before long figure out what turns out best for you.Players who haven't recently played live roulette or are curious about the principles of the game can, without losing anything, take a stab at the demo adaptation of the game with a live dealer. Basically, prior to gambling with your own genuine cash, it is prudent to appropriately rehearse your abilities with live dealers.Each club has its own client rewards. Their cautious review and search among the best web-based club rewards permit clients to rapidly and effectively start their betting excursion. What's more, most web-based gambling clubs have an instant reward bundle for new clients who enrolled. Hence, after enlistment, when you become an approved client of the internet based gambling club, you accept your welcome reward without setting aside your most memorable installment. What's more, assuming the club introduced its no store offer as a gift - don't hold back - utilize this open door quicker. Likewise, most of online club games are related with the arrival of rewards. The fantasy for any player is to join the betting local area, where you can get cashback from online gambling clubs.
You're right, online gambling is getting quite popular, and it's not surprising because it can be a great way of getting entertained. Also, many entrepreneurs work with companies like beter live - beter to develop reliable gambling platforms, and I think it's way better than working with scam websites, where you have no chance of profiting from the beginning.
Hi, football has always been and remains my favorite sport. Watching football matches, as well as all the sports news for me is not only a pleasure, but also a profit. The fact is that I am very well versed in this sport and I bet on it. On sports betting, I have chosen popular and reliable bookmakers, where I bet at the same time, but on different odds, since they are slightly different.
Hello. I think there is no better sport to bet on than football. You need help if you are inexperienced in which case you will make correct predictions and win money on your bets. For example, I only work with football, if you are also interested in this sport, you can get more information here and bookmakers comparison. Good luck and big wins.
I understand your logic, but this is not a stack operation. The only thing you can do is push and pop. You are accessing the 1st stack elements by index in the array.
Correct thing to do is push all the poped elements from first stack into a 3rd stack and pop back again while you traverse through second one.
From this problem/solution you may learn that data structures can be used in different ways, or even modify them to better fit the problem. Consider for example solving the classic stack with max where all the operations are O(1), i.e. without looping.
Same here! Since you always have two choices for your next pick, I figured a binary search tree was the obvious answer, but no! If you take the top two from each stack, our way calculates all six paths to get that same one answer! What an exponential waste! And I thought I was so clever while coding it!
hahaha, happened the same to me. I even tried improving this by considering the zero scenarios, that is if there are zeros I would navigate recursively only until the next non-zero element, also, I tried improving it by checking if it's convenient navigating further, given the current global Max.
Nice approach.
if we try greedy then there is problem in case where both corrosponding stack have same elements.
Actually if we have problem in traversing both the stack
simultaneously the best approach is to first traverse the 1st stack then start traversing second stack and manupulate the last
added element from 1st stack as required in question.
That's not the only problem in greedy. Consider this:
A = {10, 0, 0, 0, 0, 0}
B = {9, 10, 10, 10, 10}
Max = 18
In this case, greedy solution fails miserably.
One thing is clear from other comments here, the greedy solution will NOT work.
None of the explanations in the comment section are good at explaining how/why the given c++ solution by vkreddy21 works. I have tried explaining it below .....
So far only 1 thing is clear in the solution: When elements from 2nd stack are added, and (more recently added/last) elements from 1st stack are popped off, the solution ensures that the max count does not decrease and sum <= x (given in input).
Graphically:
A much better way to understand this is to think about what the final solution to the problem will look like.
For example, a possible solution could look like:
[s1 s2 s1 s2 s2 ]
where s1, s2 refer to some element from stack 1 and 2 respectively.
It may be noted that all s1 elements are contiguous (since problem requires us to only pick from top of stack). Same for s2 elements.
Now, since these elements are summed (which should be <= x), this means *they can be arranged in any order. So you could group all s1 accesses and then s2 accesses * (could have also done vice-versa). this is obviously correct because for "+" operator (using which sum is being calculated) does not care about order of operands.
Hence, our previous solution can be re-arranged to look like any of the following:
[s2 s2 s2 s1 s1 ]
(OR)
[s1 s1 s2 s2 s2]
What the second case ^ suggests is that you can create a solution like:
[s1 s1 s1 s1 s1]
and then add (or replace s1 elements if sum is exceeding "x") s2 elements one by one, eventually leading to
[s1 s1 s2 s2 s2] = [s1 s2 s1 s2 s2 ]
Note that ^ this final solution is same as the ^ solution (simply created as an example for this explanation) in the earlier part of this explanation.
You can do this by incrementing and decrementing "count" value when array[b] adding operation is going on, but it'll be difficult to remember max count!
So, it is just a simpler way.
**I used same logic but few test cases did not pass:
here is my correction in python 3 : **
*def twoStacks(x, a, b):
s=0
i=j=count=0
while len(a)>0 and i<len(a) and (s+a[i])<=x:
s+=a[i]
i+=1
count=i
while j<len(b) and i>=0:
s+=b[j]
j+=1
while s>x and i>=0:
i-=1
s-=a[i]
if s<=x and i+j >= count:
count=i+j
return count*
Above is the best solution, with O(n + m) time and O(1) space.
I tried do BFS. First attempt, passed the simple cases, but failed majority of cases.
Second attempt, I added a visted memo check using set where the memo was code snip below. Where I count the As and Bs in the search did a bit shift on Acount | with Bcount.. and this did passed more tests than first try, but still failed to pass 100% of the cases.
The set<> memo check made my BFS solution O(n+m*log(dc)) where (dc) is the distinct counts of As and Bs that are possible in the BFS. As the count score increases, (dc) gets larger and it's log(dc) because sets<> are binary search trees in c++.
Not fast enough to pass all the cases... go with the above solution.
You cannot keep on adding smaller-top elements. For eg :
a=[4, 2, 5, 4, 5]
b=[6, 1, 2, 1 ,3 ]
and let x=10. Here you should pop from b(ie, 6) inorder to get the maximum number of steps.
i have a doubt...
in the while loop where you are adding b[j] to the sum you are probably deleting more that one element in the nested while loop below it, whic makes the number of integers less for the same value of sum.****
hello there, i was wondering...
can this problem can be seen as kind of greedy for selecting maximum number of integers, as the given number can be seen as capacity and you have to select minimum of two stack tops inorder to add to the current sum, lesser current sum means more integers can be selected. if current sum exceeds capacity number of integers selected is the answer.
Actually what we want to do is to check all possible combinations(which can be obtained by popping from either stacks) ,with the sum lesser than the capacity and choose the one one with maximum number of integers.
hey, why can't we do in a greedy way. Like taking min(stack1.top(), stack2.top()) and adding to the sum. with greedy i won't get correct answer i have tried. can you please explain the second while loop and while greedy will not work.... thank you..
for anyone wondering its actually the bottom element of first stack being subtracted since 'i' is at the bottom element in the beginning and is reducing every time by one.
According to the question the program should terminate, player is disqualified if the sum is greater than max sum. And the question confuses saying its stack, which means I can't move the pointer to previous element once its read.
This algorithm works because it outputs count right, though violates sum:
Nick is disqualified from the game if, at any point, his running sum becomes greater than maxSum given at the beginning of the game.
In the while loop i--, sum -= a(i), after i reached 0, the algorithm should do the same loop with j (stack B) because sum still > maxSum. (For example testcase 0: https://ibb.co/vjxWpwT)
The next if statement, the condition shouldn't contain i + j > count because it means count only keeps the highest record --> This is why the algorithm outputs right.
What's the logic of decrementing i in the inner loop first and then subtracting that index, instead we can subtract that index from the sum and then decrement the index.
Although your solution is working but, I didn't get that part.
Game of Two Stacks
You are viewing a single comment's thread. Return to all comments →
My c++ solution
Good solution. Can you explain how did you come up with this solution? Thanks.
first I'm only considering one stack and calculating the sum and count number.Then I'm adding one element from second stack at a time to the calculated sum and comparing it with required sum.If the calculated sum is greater we subract the last added element of first stack from sum.
what's the reason for i>=0 checking in the outer while loop ? I think the code should work without this.
It just restricts extra passes, since when i<0 you know that in the sum there are only numbers of second stack, you have already subtracted all the numbers of first stack. And now no need to continue.
I agree with @farhan_tanvir_u1, the way you have it coded. The second stack will be checked to the end, once the first stack has been totally depleted, and the second stack holds all the numbers, it will not stop. Suggest adding an additional check for sum <= x. Once i = 0 && sum > x, you can stop checking the second stack.
here is problem solution in python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-game-of-two-stacks-solution.html
here is problem solution in python java c++ and c programming. https://code.programmingoneonone.com/2020/09/game-of-two-stacks-solution-hackerrank.html
yes that condition is unnecessary because i will never be negative because of the (i>0) check in inner while loop. The code can be modified to save few iterations by introducing a check if(sum>x) break; after the inner while loop.
One of the games in test case 01 got me, your approach was very clever, help me rethink my approach, thank you.
i was still confused after reading this but my realization below helped clarify; so for those who still may be confused:
the whole idea of adding the recently popped 2nd stack element to the sum and removing the last 1st stack element if the sum is greater than the sum limit is to maintain the max count thus far.
therefore, the max count will never decrease and will only increase if either 1) we can add an element from the 2nd stack without removing from the sum or 2) removing an "added element from 1st stack" allows for 2 or more additional elements from 2nd stack.
even after looking at code , i was still confused, thanks to your comment, you exactly knew how i was struggling to think.
perfect explanation of that code. thanks for comment
Thanks, finally I did it!!
here is problem solution in python java c++ c and javascript programming.
HackerRank Game of Two stacks solution
Here is my code in java...
Where are you using stacks st1 & st2?
That's true. You have just initialzed the stack and pushed the data but nowhere using those references (st1 & st2) in your business logic...
what's the logic of decrementing lengthB first and then subrtracting the it from sum instead why can't we subtract it first and then decrement the index.
The famous Drunken Roulette with Stacks is one of the most popular casino games. Now you can try your luck at home too.
Hey! I was recently looking for something new in online games and came across Aviator. The game is pretty engaging and feels fair, which really caught my attention. I found a clear explanation of how its fairness system works on https://aviator-games.co.za/provably-fair-aviator/ — worth a read if you're curious about how these mechanics are set up.
The famous Drunken Roulette with Stacks is one of the most popular casino games. Now you can try your luck at home too.
awesome logic
here is problem solution in python java c++ and c programming. https://programs.programmingoneonone.com/2021/05/hackerrank-game-of-two-stacks-solution.html
Online club are acquiring fans, whenever contrasted with exemplary betting clubs. These days, players have the amazing chance to remain in an agreeable climate at home, and simultaneously take an interest in the round of roulette, finding a seat at a virtual web-based table. Assuming you are another player to the web-based roulette game and need to find success, you want to get to know the 7 fundamental standards of the game and, obviously, stick to them. There are 7 best ways to play live dealer roulette that each client should follow.It is fundamental for every player to draw an individual line for themselves. The initial and most significant stage before inundation into the universe of online gambling clubs is to contemplate and decide your bankroll plainly. Prior to beginning the game, decide how much cash you will spend in a web-based gambling club. Additionally, a web-based club can offer the assistance of a store limit, a bet breaking point, and, surprisingly, a cutoff on the span of the game.To pick a decent web-based club, ensure that it likewise has a permit to work from one of the authorized betting networks: UK Gambling Committee, Curacao Licensed Committee, Malta Gambling Committee, Gibraltar Gambling License, Supervisory Gambling Commission. Furthermore, prior to joining an internet based club, every player ought to look into the terms of collaboration. The player ought to peruse and grasp the standards of the club, as they can be totally disparate in each web-based club, and have similar significance as the license.Despite the gigantic choice of live dealer roulette, most players have their number one virtual table, which they would rather not change. In the event that you actually haven't observed the club name that suits you best, just relax. There is a finished top rundown of live gambling club games accessible on such world class assets as PlayTech, Pragmatic Play, Evolution Gaming. Each game has its own guidelines, and as you foster your playability, you can before long figure out what turns out best for you.Players who haven't recently played live roulette or are curious about the principles of the game can, without losing anything, take a stab at the demo adaptation of the game with a live dealer. Basically, prior to gambling with your own genuine cash, it is prudent to appropriately rehearse your abilities with live dealers.Each club has its own client rewards. Their cautious review and search among the best web-based club rewards permit clients to rapidly and effectively start their betting excursion. What's more, most web-based gambling clubs have an instant reward bundle for new clients who enrolled. Hence, after enlistment, when you become an approved client of the internet based gambling club, you accept your welcome reward without setting aside your most memorable installment. What's more, assuming the club introduced its no store offer as a gift - don't hold back - utilize this open door quicker. Likewise, most of online club games are related with the arrival of rewards. The fantasy for any player is to join the betting local area, where you can get cashback from online gambling clubs.
You're right, online gambling is getting quite popular, and it's not surprising because it can be a great way of getting entertained. Also, many entrepreneurs work with companies like beter live - beter to develop reliable gambling platforms, and I think it's way better than working with scam websites, where you have no chance of profiting from the beginning.
Hi, football has always been and remains my favorite sport. Watching football matches, as well as all the sports news for me is not only a pleasure, but also a profit. The fact is that I am very well versed in this sport and I bet on it. On sports betting, I have chosen popular and reliable bookmakers, where I bet at the same time, but on different odds, since they are slightly different.
Hello. I think there is no better sport to bet on than football. You need help if you are inexperienced in which case you will make correct predictions and win money on your bets. For example, I only work with football, if you are also interested in this sport, you can get more information here and bookmakers comparison. Good luck and big wins.
I understand your logic, but this is not a stack operation. The only thing you can do is push and pop. You are accessing the 1st stack elements by index in the array.
Correct thing to do is push all the poped elements from first stack into a 3rd stack and pop back again while you traverse through second one.
Using an index on an array in this manner is essentially the same thing as a stack. Its more efficient.
I agree with emarsc's comment.
From this problem/solution you may learn that data structures can be used in different ways, or even modify them to better fit the problem. Consider for example solving the classic stack with max where all the operations are O(1), i.e. without looping.
Formally you're right, but you can easily replace indexing with buffer stack. Logic itself will not change.
You are right, and those who uses index, what would you do if you are given a stack implemented with linkedlist? there will be no index to use
but where is the use of stack or atleast its concept
See emarsc's comment.
good logic my brute force solution recursive is showing timeout for almost half of cases
Same here! Since you always have two choices for your next pick, I figured a binary search tree was the obvious answer, but no! If you take the top two from each stack, our way calculates all six paths to get that same one answer! What an exponential waste! And I thought I was so clever while coding it!
hahaha, happened the same to me. I even tried improving this by considering the zero scenarios, that is if there are zeros I would navigate recursively only until the next non-zero element, also, I tried improving it by checking if it's convenient navigating further, given the current global Max.
are u not facing timeout problem in some of the test cases?
Implemented the same way on java. P.S.: With Scanner(System.in) the last test fails with TLE. Use Fast I/O to resolve this.
Nice approach. if we try greedy then there is problem in case where both corrosponding stack have same elements. Actually if we have problem in traversing both the stack simultaneously the best approach is to first traverse the 1st stack then start traversing second stack and manupulate the last added element from 1st stack as required in question.
That's not the only problem in greedy. Consider this:
A = {10, 0, 0, 0, 0, 0}
B = {9, 10, 10, 10, 10}
Max = 18
In this case, greedy solution fails miserably.
It gives correct answer but wrong numbers are added to the sum in following test case:
1
3 3 4
1 1 1
99 2 0
One thing is clear from other comments here, the greedy solution will NOT work.
None of the explanations in the comment section are good at explaining how/why the given c++ solution by vkreddy21 works. I have tried explaining it below .....
So far only 1 thing is clear in the solution: When elements from 2nd stack are added, and (more recently added/last) elements from 1st stack are popped off, the solution ensures that the max count does not decrease and sum <= x (given in input).
Graphically:
A much better way to understand this is to think about what the final solution to the problem will look like.
For example, a possible solution could look like:
where s1, s2 refer to some element from stack 1 and 2 respectively. It may be noted that all s1 elements are contiguous (since problem requires us to only pick from top of stack). Same for s2 elements.
Now, since these elements are summed (which should be <= x), this means *they can be arranged in any order. So you could group all s1 accesses and then s2 accesses * (could have also done vice-versa). this is obviously correct because for "+" operator (using which sum is being calculated) does not care about order of operands.
Hence, our previous solution can be re-arranged to look like any of the following:
(OR)
What the second case ^ suggests is that you can create a solution like:
and then add (or replace s1 elements if sum is exceeding "x") s2 elements one by one, eventually leading to
Note that ^ this final solution is same as the ^ solution (simply created as an example for this explanation) in the earlier part of this explanation.
Clear and concise!
Thanks Dheeraj !
Hey,i cannot understand the editorial's logic and you people are following the same logic.Why you are removing element of stack A and how does it maximises the answer? Is there any other logic? Link to my code is below: https://www.hackerrank.com/challenges/game-of-two-stacks/submissions/code/124747035
Can you improve my code so that it doesn't get terminated due to timeout?
have u deleted your code??
can someone please tell the meaning of the last if condition?
He is just maintaining the max count when sum<=x
You can do this by incrementing and decrementing "count" value when array[b] adding operation is going on, but it'll be difficult to remember max count! So, it is just a simpler way.
**I used same logic but few test cases did not pass: here is my correction in python 3 : **
*def twoStacks(x, a, b):
For the above case, your program gives 6. But the correct answer is 5.
Above is the best solution, with O(n + m) time and O(1) space.
I tried do BFS. First attempt, passed the simple cases, but failed majority of cases.
Second attempt, I added a visted memo check using set where the memo was code snip below. Where I count the As and Bs in the search did a bit shift on Acount | with Bcount.. and this did passed more tests than first try, but still failed to pass 100% of the cases.
The set<> memo check made my BFS solution O(n+m*log(dc)) where (dc) is the distinct counts of As and Bs that are possible in the BFS. As the count score increases, (dc) gets larger and it's log(dc) because sets<> are binary search trees in c++.
Not fast enough to pass all the cases... go with the above solution.
Seriously it was helpful..I was popping the smaller element from the two stacks ...And getting wrong answers.. Thanks a ton for the cool logic
Here is my js solution, but it's not passing the whole testcases because of timeout, help me to figure out.
You cannot keep on adding smaller-top elements. For eg : a=[4, 2, 5, 4, 5] b=[6, 1, 2, 1 ,3 ] and let x=10. Here you should pop from b(ie, 6) inorder to get the maximum number of steps.
i have a doubt... in the while loop where you are adding b[j] to the sum you are probably deleting more that one element in the nested while loop below it, whic makes the number of integers less for the same value of sum.****
with the same approach, using C, Im getting a TLE for TestCase 8
hello there, i was wondering... can this problem can be seen as kind of greedy for selecting maximum number of integers, as the given number can be seen as capacity and you have to select minimum of two stack tops inorder to add to the current sum, lesser current sum means more integers can be selected. if current sum exceeds capacity number of integers selected is the answer.
Actually what we want to do is to check all possible combinations(which can be obtained by popping from either stacks) ,with the sum lesser than the capacity and choose the one one with maximum number of integers.
hey, why can't we do in a greedy way. Like taking min(stack1.top(), stack2.top()) and adding to the sum. with greedy i won't get correct answer i have tried. can you please explain the second while loop and while greedy will not work.... thank you..
Greedy will not work in the case when the result depends upon the subsequent elements after the top element. Example Let,
Stack_a : Top -> 4 1 1 7 8
Stack_b : Top -> 3 3 1 2 3
If, the target sum is X = 6,
Then, on selecting the smaller Top element, i.e., 3 (Stack_b.Top) we can only get two of the top elements: <3, 3>
But, if we go with the Top element of Stack_a, i.e., 4 we can get to the three top elements: <4, 1, 1>
I'm getting runtime error for testcase 5 while using this logic in C, can you explain why?
If you share your code then it would be easy to point out any bug.
doubt. in the outer while loop, negative value of i will not come right?
nice solution !!!
nice one man...how you think soo deep I can't even think around your solution...
your approach is really good .
very nice
Fabulous! How did you get it?
Amazing logic man!! Hat's off!
for anyone wondering its actually the bottom element of first stack being subtracted since 'i' is at the bottom element in the beginning and is reducing every time by one.
I uesed Linked List to solve this problem
i cant understand and its not work properly
amazing!!
and this is O(n) ritght?
According to the question the program should terminate, player is disqualified if the sum is greater than max sum. And the question confuses saying its stack, which means I can't move the pointer to previous element once its read.
This algorithm works because it outputs count right, though violates sum:
Nick is disqualified from the game if, at any point, his running sum becomes greater than maxSum given at the beginning of the game.
Sum up: https://ibb.co/v1RxQk7
With this modification, the algorithm will be exactly the author beginning idea. But it leads to infinite loops.
So the "hacking" part is violates sum condition.
can you tell time complexity of this algorithm
What's the logic of decrementing i in the inner loop first and then subtracting that index, instead we can subtract that index from the sum and then decrement the index. Although your solution is working but, I didn't get that part.