python code that beats 100%, but quite verbose


  • 0
    Y
    class Solution(object):
        def wiggleMaxLength(self, nums):
            if len(nums) == 0: return 0
            if max(nums) == min(nums): return 1
            count, current = 0, nums[0]
            state, start = None, 0
            for i in range(1, len(nums)):
                if nums[i] != current:
                    if nums[i] > current:
                        state = 1 
                    else:
                        state = -1 
                    current = nums[i]
                    start = i
                    break
                count += 1
            for j in range(start+1, len(nums)):
                if state > 0 and nums[j] >= current:
                    current = max(current, nums[j])
                    count += 1
                    continue
                if state < 0 and nums[j] <= current:
                    current = min(current, nums[j])
                    count += 1
                    continue
                if state > 0 and nums[j] < current:
                    current = nums[j]
                    state = -1
                elif state < 0 and nums[j] > current:
                    current = nums[j]
                    state = 1
            return len(nums) - count
    

    Guess I'm too lazy now to optimize the code... but the idea is to greedily keep the local maxima or minimum


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.