Skip to content

376. Wiggle Subsequence 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int wiggleMaxLength(vector<int>& nums) {
    int increasing = 1;
    int decreasing = 1;

    for (int i = 1; i < nums.size(); ++i)
      if (nums[i] > nums[i - 1])
        increasing = decreasing + 1;
      else if (nums[i] < nums[i - 1])
        decreasing = increasing + 1;

    return max(increasing, decreasing);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int wiggleMaxLength(int[] nums) {
    int increasing = 1;
    int decreasing = 1;

    for (int i = 1; i < nums.length; ++i)
      if (nums[i] > nums[i - 1])
        increasing = decreasing + 1;
      else if (nums[i] < nums[i - 1])
        decreasing = increasing + 1;

    return Math.max(increasing, decreasing);
  }
}