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);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def wiggleMaxLength(self, nums: list[int]) -> int:
    increasing = 1
    decreasing = 1

    for a, b in itertools.pairwise(nums):
      if b > a:
        increasing = decreasing + 1
      elif b < a:
        decreasing = increasing + 1

    return max(increasing, decreasing)