0

This is the 1st time I am trying coding practices on platform like SPOJ. I have used bottom-up approach of dynamic programming and I am submitting below solution for finding maximum length of alternating sub-sequence of +ve and -ve numbers. It is variation of program longest increasing sub-sequence of array.It shows Time Limit Exceeded. Can someone please tell me how can I optimize the below program further? P.S. This solution is successfully submitted on hackerEarth platform

def alternatingSeq(arr,n):
    if(n==1):
        return 1

    dp = [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))
2
  • What's the program supposed to do? Commented May 10, 2020 at 17:44
  • @AKX I edited the question. let me know if it is still unclear. Thanks Commented May 10, 2020 at 17:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.