Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def longestAlternating(self, nums):7 """8 :type nums: List[int]9 :rtype: int10 """11 result = up1 = up0 = down1 = down0 = 112 for i in xrange(len(nums)-1):13 if nums[i] < nums[i+1]:14 up1, up0, down1, down0 = down1+1, down0+1, down0, 115 elif nums[i] > nums[i+1]:16 up1, up0, down1, down0 = up0, 1, up1+1, up0+117 else:18 up1, up0, down1, down0 = up0, 1, down0, 119 result = max(result, up1, down1)20 return result21 22 23242526class Solution2(object):27 def longestAlternating(self, nums):28 """29 :type nums: List[int]30 :rtype: int31 """32 result = up0 = down0 = 133 up1 = down1 = 034 for i in xrange(len(nums)-1):35 if nums[i] < nums[i+1]:36 up1, up0, down1, down0 = down1+1, down0+1, down0, 137 elif nums[i] > nums[i+1]:38 up1, up0, down1, down0 = up0, 1, up1+1, up0+139 else:40 up1, up0, down1, down0 = up0, 1, down0, 141 result = max(result, up1, down1, up0, down0)42 return result43 44 45464748class Solution3(object):49 def longestAlternating(self, nums):50 """51 :type nums: List[int]52 :rtype: int53 """54 left = [1]*len(nums)55 for i in xrange(1, len(nums)):56 diff = cmp(nums[i-1], nums[i])57 if not diff:58 continue59 left[i] = left[i-1]+1 if i-2 >= 0 and cmp(nums[i-2], nums[i-1]) == -diff else 260 right = [1]*len(nums)61 for i in reversed(xrange(len(nums)-1)):62 diff = cmp(nums[i], nums[i+1])63 if not diff:64 continue65 right[i] = right[i+1]+1 if i+2 < len(nums) and cmp(nums[i+1], nums[i+2]) == -diff else 266 result = max(left)67 for i in xrange(1, len(nums)-1):68 diff = cmp(nums[i-1], nums[i+1])69 if not diff:70 continue71 l = (left[i-1] if i-2 >= 0 and cmp(nums[i-2], nums[i-1]) == -diff else 1)72 r = (right[i+1] if i+2 < len(nums) and cmp(nums[i+1], nums[i+2]) == -diff else 1)73 result = max(result, l+r)74 return result75