Wiggle Subsequence in C++

C++Server Side ProgrammingProgramming

Suppose we have a sequence of numbers that is called a wiggle sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference may be either positive or negative. A sequence with less than two elements is trivially a wiggle sequence. So for example, [1,7,4,9,2,5] is a wiggle sequence because if you see, the differences (6,-3,5,-7,3) are alternately positive and negative. But, [1,4,7,2,5] and [1,7,4,5,5] are not wiggle sequences, the first one because its first two differences are positive and the second one because its last difference is zero.

So we have a sequence of integers, we have to find the length of the longest subsequence that is a wiggle sequence. A subsequence is obtained by deleting some number of elements (eventually, also zero) from the original sequence, leaving the remaining elements in their original order. So if the input is like [1,7,4,9,2,5], then the output will be 6. as the entire sequence is a wiggle sequence.

To solve this, we will follow these steps −

  • n := size of nums

  • if n is 0, then return 0

  • set up := 1 and down := 1

  • for i in range 1 to n – 1

    • if nums[i] > nums[i – 1], then up := down + 1

    • otherwise when nums[i] < nums[i – 1], then down := up + 1

  • return max of up and down

Example (C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int wiggleMaxLength(vector<int>& nums) {
      int n = nums.size();
      if(!n) return 0;
      int up = 1;
      int down = 1;
      for(int i = 1; i < n; i++){
         if(nums[i] > nums[i - 1]){
            up = down + 1;
         }
         else if(nums[i] < nums[i - 1]){
            down = up + 1;
         }
      }
      return max(up, down);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,7,4,9,2,5};
   cout << (ob.wiggleMaxLength(v));
}

Input

[1,7,4,9,2,5]

Output

6
raja
Published on 02-May-2020 11:43:04
Advertisements