1 / 3
May 2020

I am submitting this code snippet of python 3.4 in problem ALTSEQ and it always gives TLE. Can anyone please help me and guide how to optimize this further?

def alternatingSeq(arr,n):
    if(n==1):
        return 1dp = [1 for i in range(n)]

     res = 0
     for i in range(1,n):

     for j in range(i):
        if( ((arr[i]<0 and arr[j] > 0 and -arr[i] > arr[j])
        or (arr[i]>0 and arr[j] < 0 and arr[i] > -arr[j])) 
        and dp[i] < 1 + dp[j]):
            dp[i] = 1 + dp[j]


      if(dp[i] > res):
        res = dp[i]

   return res

   n = int(input())
   arr = [int(i) for i in input().split()] 
   print(alternatingSeq(arr,n))
  • created

    May '20
  • last reply

    May '20
  • 2

    replies

  • 583

    views

  • 2

    users

  • 1

    like

Your solution gets AC in PyPy, just change input() to raw_input(). Problems of this kind are often impossible to pass here in pure Python.

As the problem is set with many single-case testfiles, the runtime is heavily distorted by interpreter startup lag so you won’t see much of a result of optimizations. However it’s always better to use variables rather than sequence access if possible, also simplifying the operations within the nested loops could help. Here’s how I’d write it:

def alternating_seq(a, n):
    if n == 1:
        return 1
    dp = [1] * n
    res = 0
    for i, vi in enumerate(a[1:], 1):
        dpi = 1
        for j, vj in enumerate(a[:i]):
            if dpi <= dp[j] and (-vi > vj > 0 or vi > -vj > 0):
                dpi = 1 + dp[j]
        if dpi > res:
            res = dpi
        dp[i] = dpi
    return res

n = int(input())
a = [int(i) for i in input().split()] 
print(alternating_seq(a, n))

PS. Watch out when using list slicing in a loop in PyPy, sometimes it’s heavy on the memory.

Thank you so much for explaining it in detail actually I am new to this platform and beginner in python.
I tried submitting your solution and it is giving runtime error (NZEC). Can you please help me out?