• + 43 comments

    My c++ solution

    #include <bits/stdc++.h>
    
    using namespace std;
    
    int main(){ 
        int g;
        cin >> g;    
        for(int a0 = 0; a0 < g; a0++){
            int n;
            int m;
            int x;
            cin >> n >> m >> x;
            
            vector<int> a(n);
            for(int a_i = 0; a_i <n; a_i++){
               cin >> a[a_i];
            }
            
            vector<int> b(m);
            for(int b_i =0; b_i <m; b_i++){
               cin >> b[b_i];
            }
            
            int sum=0,count=0,temp=0,i=0,j=0;        
            
            while(i<n && sum+a[i]<=x){    //considering only first stack and calculating count
                sum+=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;
        } 
        return 0;
    }
    
    • + 5 comments

      Good solution. Can you explain how did you come up with this solution? Thanks.

      • + 3 comments

        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.

        • + 4 comments

          what's the reason for i>=0 checking in the outer while loop ? I think the code should work without this.

          • + 2 comments

            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.

            • + 1 comment

              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.

          • + 0 comments

            here is problem solution in python java c++ and c programming. https://solution.programmingoneonone.com/2020/07/hackerrank-game-of-two-stacks-solution.html

          • + 0 comments

            here is problem solution in python java c++ and c programming. https://code.programmingoneonone.com/2020/09/game-of-two-stacks-solution-hackerrank.html

          • + 0 comments

            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.

        • + 0 comments

          One of the games in test case 01 got me, your approach was very clever, help me rethink my approach, thank you.

        • + 3 comments

          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.

          • + 0 comments

            even after looking at code , i was still confused, thanks to your comment, you exactly knew how i was struggling to think.

          • + 0 comments

            perfect explanation of that code. thanks for comment

          • + 0 comments

            Thanks, finally I did it!!

      • + 0 comments

        here is problem solution in python java c++ c and javascript programming.

        HackerRank Game of Two stacks solution

      • + 2 comments

        Here is my code in java...

        public static int twoStacks(int maxSum, List<Integer> a, List<Integer> b) {
            // Write your code here
            Stack<Integer> st1 = new Stack<>();
            Stack<Integer> st2 = new Stack<>();
            for(int i=0; i<a.size(); i++){
              st1.push(a.get(i));
            }
            for(int i=0; i<b.size(); i++){
              st2.push(b.get(i));
            }
            int lengthB=0;
            int sum = 0;
            while(lengthB<b.size() && (sum+b.get(lengthB)) <= maxSum ){
              sum += b.get(lengthB);
              lengthB++;
            }
            int maxScore = lengthB;
            for(int i=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 );
            }
            return maxScore;
        
            }
        
        • + 1 comment

          Where are you using stacks st1 & st2?

          • + 1 comment
            Stack<Integer> st1 = new Stack<>();
                Stack<Integer> st2 = new Stack<>();
                for(int i=0; i<a.size(); i++){
                  st1.push(a.get(i));
                }
                for(int i=0; i<b.size(); i++){
                  st2.push(b.get(i));
                }
            
            • + 0 comments

              That's true. You have just initialzed the stack and pushed the data but nowhere using those references (st1 & st2) in your business logic...

        • + 0 comments

          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.

      • + 5 comments

        The famous Drunken Roulette with Stacks is one of the most popular casino games. Now you can try your luck at home too.

        • + 0 comments

          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.

      • + 0 comments

        The famous Drunken Roulette with Stacks is one of the most popular casino games. Now you can try your luck at home too.

    • + 2 comments

      awesome logic

      • + 0 comments

        here is problem solution in python java c++ and c programming. https://programs.programmingoneonone.com/2021/05/hackerrank-game-of-two-stacks-solution.html

      • + 3 comments

        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.

        • + 0 comments

          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.

        • + 0 comments

          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.

        • + 0 comments

          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.

    • + 4 comments

      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.

      • + 0 comments

        Using an index on an array in this manner is essentially the same thing as a stack. Its more efficient.

      • + 0 comments

        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.

      • + 0 comments

        Formally you're right, but you can easily replace indexing with buffer stack. Logic itself will not change.

      • + 0 comments

        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

    • + 1 comment

      but where is the use of stack or atleast its concept

      • + 0 comments

        See emarsc's comment.

    • + 2 comments

      good logic my brute force solution recursive is showing timeout for almost half of cases

      • + 1 comment

        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!

        • + 0 comments

          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.

    • + 0 comments

      are u not facing timeout problem in some of the test cases?

    • + 0 comments

      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.

    • + 1 comment

      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.

      • + 0 comments

        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.

    • + 0 comments

      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

    • + 2 comments

      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.

      • + 1 comment

        Clear and concise!

        • + 0 comments

          Thanks Dheeraj !

      • + 1 comment

        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?

        • + 0 comments

          have u deleted your code??

    • + 1 comment

      can someone please tell the meaning of the last if condition?

      • + 0 comments

        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.

    • + 0 comments

      **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*
      
    • + 0 comments

      1

      5 4 8

      2 1 1 1 1 10

      7 8 9

      For the above case, your program gives 6. But the correct answer is 5.

    • + 0 comments

      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.

      // Path string = "ABABBBAABB..." which gets acumulated as
      // BFS spans
      unsigned long long path_to_long(string  const & pathstr) {
        unsigned long long acount = 0;
          unsigned long long bcount = 0;
          for(int i=0; i<pathstr.length();i++) {
              switch (pathstr[i]) {
                  case 'A':
                    acount++;
                    break;
                  case 'B':
                    bcount++;
                    break;
                  default:
                    break;
              }
          }
          return ((acount << 32)|bcount);
      }	
      
    • + 0 comments

      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

    • + 1 comment

      Here is my js solution, but it's not passing the whole testcases because of timeout, help me to figure out.

      function twoStacks(x, a, b) {
          /*
           * Write your code here.
           */
          // console.log(x,a[0],b[0])   
          var count = 0
          var getsum = 0
          var terminate = 0
          while(getsum <= x){
              // console.log(getsum)
              if(a[0] <= b[0]){  
                  var check = getsum + a[0]    
                  if(check <= x){
                      a.shift()
                      getsum = getsum + a[0]
                      count++
                  }else if(check > x){
                      terminate++
                      if(terminate > 1){
                          break
                      }
                  }
                  
              }else if(b[0] <= a[0]){
                  var check1 = getsum + b[0]
                  if(check1 <= x){
                      b.shift()
                      getsum = getsum + b[0]
                      count++
                  }else if(check1 > x){
                      terminate++
                      if(terminate > 1){
                          break
                      }
                  }
              } 
              
          }
         return count
      
      }
      
      • + 0 comments

        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.

    • + 0 comments

      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.****

    • + 0 comments

      with the same approach, using C, Im getting a TLE for TestCase 8

    • + 1 comment

      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.

      • + 0 comments

        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.

    • + 1 comment

      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..

      • + 0 comments

        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>

    • + 1 comment

      I'm getting runtime error for testcase 5 while using this logic in C, can you explain why?

      • + 0 comments

        If you share your code then it would be easy to point out any bug.

    • + 0 comments

      doubt. in the outer while loop, negative value of i will not come right?

    • + 0 comments

      nice solution !!!

    • + 0 comments

      nice one man...how you think soo deep I can't even think around your solution...

    • + 0 comments

      your approach is really good .

    • + 0 comments

      very nice

    • + 0 comments

      Fabulous! How did you get it?

    • + 0 comments

      Amazing logic man!! Hat's off!

    • + 0 comments

      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.

    • + 0 comments

      I uesed Linked List to solve this problem

      import sys
      
      class Node:
          def __init__(self, data, next = None):
              self.data = data
              self.next = next
              
      class Stack:
          def __init__(self):
              self.top = None
          
          def isempty(self):
              if self.top is None:
                  return True
              return False
          
          def peek(self):
              if not self.isempty():
                  return self.top.data
              return 0
          
          def push(self, data):
              node = Node(data)
              if self.isempty():
                  self.top = node
                  return
              node.next = self.top
              self.top = node
              
          def pop(self):
              if self.isempty():
                  raise Exception("Stack Overflow")
              data = self.top.data
              self.top = self.top.next
              return data
      
      if __name__ == '__main__': 
          g = int(input())
      
          for g_itr in range(g):
              nmx = input().split()
      
              n = int(nmx[0])
      
              m = int(nmx[1])
      
              x = int(nmx[2])
      
              ni = sys.stdin.readline().strip().split()
              mi = sys.stdin.readline().strip().split()
              stack1, stack2 = Stack(), Stack()
              for i in range(n-1, -1, -1):
                  stack1.push(int(ni[i]))
      
              for i in range(m-1,-1,-1):
                  stack2.push(int(mi[i]))
      
              live_sum, i, j = 0, 0, 0
              junk = Stack()
              while not stack1.isempty() and live_sum + stack1.peek() <= x:
                  live_sum += stack1.peek()
                  junk.push(stack1.pop())
                  i += 1
              count = i
              while not stack2.isempty():
                  live_sum += stack2.pop()
                  j += 1
                  while live_sum>x and not junk.isempty():
                      i-=1
                      live_sum -= junk.pop()
                  if live_sum<=x and i+j>count:
                      count = i+j
      
              result = count
              print(result)
      
    • + 0 comments

      i cant understand and its not work properly

    • + 0 comments

      amazing!!

    • + 0 comments

      and this is O(n) ritght?

    • + 0 comments

      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.

    • + 0 comments

      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.

      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.

    • + 0 comments

      can you tell time complexity of this algorithm

    • + 0 comments

      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.