Romok007's blog

By Romok007, history, 6 years ago, In English

Hello everyone. It would be great if someone gives a solution for this problem https://www.codechef.com/problems/CZ17R2Q2. Thank you.

  • Vote: I like it
  • -1
  • Vote: I do not like it

| Write comment?
»
6 years ago, # |
Rev. 2   Vote: I like it +1 Vote: I do not like it

Maintain a stack of length n. For every i-th element, if it is positive, push it into the stack. If it is negative, let's call it x. Check if stack.top() == -x. If yes, pop stack.top() and increase the counter by 2.

Solution complexity — O(n).

  • »
    »
    6 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I think for the input : 1 2 3 -1. Your solution will give 0 as the answer whereas the ans should be 2. Correct me if i am wrong.

    • »
      »
      »
      6 years ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      How do you get answer 2 for 1 2 3 -1 ?

      • »
        »
        »
        »
        6 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        The question asks for the longest balanced subsequence. So if we take 1 -1 as the subsequence from 1 2 3 -1, we end up with a balanced subsequence of length 2.

        • »
          »
          »
          »
          »
          6 years ago, # ^ |
            Vote: I like it 0 Vote: I do not like it

          I guess you have to pick consecutive positions because for sample testcase 1 -1 2 3 -2 answer is 2 (1 and -1). The answer could be 4 (1, -1, 2, -2) if it would be allowed to pick any positions. So for input 1 2 3 -1 answer is 0.

»
6 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Basically, you have to find the largest subarray whose sum is equal to zero. You can look at my submission here