Easy to understand, O(n) time O(1) space


  • 0
    Z
    int wiggleMaxLength(vector<int>& nums) {
        int len = nums.size();
        if (len < 2)
            return len;
        int status = 0;       // 1 for rising, -1 for falling, 0 for not desicded yet.
        int seq_len = 1;          // the minimum sequence length should be 1
        for (int i=1;i<len;i++) {     //start checking from second num
            int diff = nums[i] - nums[i-1];      // get diff of current and previous num
            if (diff == 0)    // skip same number
                continue;
            if (status == 0 || diff * status < 0) {       // if the trend is different from previous
                seq_len++;      // increase sequence length
                status = diff > 0? 1:-1;       // record current trend
            }
        }
        return seq_len;
    }

Log in to reply
 

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