Iam_Sandeep

Longest Alternatin Subsequence DP MEMO STATE ITERATIVE

May 7th, 2022
1,054
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.86 KB | None | 0 0
  1.  
  2. class Solution:
  3.     def AlternatingaMaxLength(self, nums):
  4.         dp={}
  5.         #J--->True means go for increasing
  6.         #j--->False means go for dereassing
  7.         n=len(nums)
  8.         def help(i,j):
  9.             if i<0 or j<0 or i==n or j==n:return 0
  10.             if (i,j) in dp:return dp[(i,j)]
  11.             if j==True and nums[i]>nums[i-1]:
  12.                     ans=max(1+help(i+1,False),help(i+1,True))
  13.             elif j==False and nums[i]<nums[i-1]:
  14.                     ans=max(1+help(i+1,True),help(i+1,False))
  15.             else:
  16.                 ans=help(i+1,j)
  17.             dp[(i,j)]=ans
  18.             return ans
  19.         return 1+max(help(1,True),help(1,False))
  20. #iterative
  21.  
  22. class Solution:
  23.     def AlternatingaMaxLength(self, nums):
  24.         dp=[0]*(n)
  25.         downs=[1]*n
  26.         ups=[1]*n
  27.         for i in range(1,n):
  28.             for j in range(i):
  29.                 if nums[i]>nums[j]:
  30.                     ups[i]=max(ups[i],1+downs[j])
  31.                 elif nums[i]<nums[j]:
  32.                     downs[i]=max(downs[i],1+ups[j])
  33.         return max(ups[-1],downs[-1])
  34.            
  35. #O(1) state approach
  36.  
  37. class Solution:
  38.     def AlternatingaMaxLength(self, nums):
  39.         ups=downs=1
  40.         '''
  41.         This problem boils to find no of max(hills, valleys) in the given graph.
  42.        This is Greedy approach
  43.        Watch a youtube video
  44.        In increasing sequence T you always select the greatest element of T so that you can have
  45.        the chance of more least elements of next sequence.---->No of ups
  46.        
  47.        In Decreasing sequence T you always select the lowest element of T so that you can have
  48.        the chance of more greater elements of next sequence.--->No of downs
  49.         '''
  50.         for i in range(1,n):
  51.             if nums[i]>nums[i-1]:
  52.                 ups=downs+1
  53.             #ignore nums[i]==nums[i-1] because theya are not in alternative
  54.             #subseqeunce
  55.             elif nums[i]<nums[i-1]:
  56.                 downs=ups+1
  57.         return max(ups,downs)
  58.  
Advertisement
Add Comment
Please, Sign In to add comment