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