Thinking in wave-forms - simple approach


  • 0
    K

    If we plot the sequence as a wave-form, all we need is to keep track of the number of peaks and valleys. A peak or a valley is a point at which the sign of the slope flips. if at any point, the sign of the slope is the same as the previous, we are continuing in an ascent or a descent and that point does not add the count. Also if the slope is 0, then the current point is at the same level as the previous and hence can also be ignored.

    class Solution(object):
        def wiggleMaxLength(self, nums):
            if not nums:
                return 0
            lastsign = 0
            count = 1
            for i in range(1,len(nums)):
                diff = nums[i]-nums[i-1]
                # Slope is 0
                if (diff == 0):
                    continue
                sign = diff/abs(diff)
                # Slope has changed
                if sign != lastsign:
                    count += 1
                    lastsign = sign
            return count
    

Log in to reply
 

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