Leetcode 376 Solution

This article provides solution to leetcode question 376 (wiggle-subsequence)

https://leetcode.com/problems/wiggle-subsequence

Solution

class Solution {
public:
    int wiggleMaxLength(vector<int>& nums) {
        int dir = 0;
        int total = 0;

        for (int i = 0; i < nums.size(); i++)
        {
            if (i == 0)
                total++;
            else
            {
                if (dir == 0)
                {
                    if (nums[i] > nums[i - 1])
                        dir = 1, total++;
                    else if (nums[i] < nums[i - 1])
                        dir = -1, total++;
                }
                else if (dir == 1)
                {
                    if (nums[i] < nums[i - 1])
                        dir = -1, total++;
                }
                else if (dir == -1)
                {
                    if (nums[i] > nums[i - 1])
                        dir = 1, total++;
                }
            }
        }

        return total;
    }
};