376. Wiggle Subsequence ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class 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 14class 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 12class 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)