Longest alternating subsequence | Practice | GeeksforGeeks

A sequence {x1, x2, .. xn} is alternating sequence if its elements satisfy one of the following relations :
x1 < x2 > x3 < x4 > x5..... or  x1 >x2 < x3 > x4 < x5.....
Your task is to find the longest such sequence.

Example 1:
Input: nums = {1,5,4}
Output: 3
Explanation: The entire sequenece is a 
alternating sequence.

Examplae 2:
Input: nums = {1,17,5,10,13,15,10,5,16,8}
Output: 7
Explanation: There are several subsequences
that achieve this length. 
One is {1,17,10,13,10,16,8}.

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function AlternatingaMaxLength() which takes the sequence  nums as input parameter and returns the maximum length of alternating sequence.

Expected Time Complexity: O(n)
Expected Space Complexity: O(1)

Constraints:
1 <= n <= 105
0
milindprajapatmst193 weeks ago
Total Time Taken: 0.19/1.43
Time Complexity: O(n)
Space Complexity: O(1)
Idea: Greedy
 
class Solution {
	public:
	int help(int k, vector<int>& nums) {
	    int last = nums[0], len = 1;
	    for (int i = 1; i < nums.size(); i++) {
	        if (k) { // look for > last
	            if (nums[i] > last) {
	                len++;
	                k = 0;
	                last = nums[i];
	            }
	            else
	                last = min(last, nums[i]);
	        }
	        else { // look for < last
	            if (nums[i] < last) {
	                len++;
	                k = 1;
	                last = nums[i];
	            }
	            else
	                last = max(last, nums[i]);
	        }
	    }
	    return len;
	}
	int AlternatingaMaxLength(vector<int>& nums) {
	    return max(help(0, nums), help(1, nums));
	}
};
-3
maheshahirwar2041 month ago
Best Java Solution TC - O(N) SC - O(1) 
and also easy to understand solution....
 
 
class Solution{   public int AlternatingaMaxLength(int[] nums)   {      int ans1=1,ans2=1;      for(int i=1;i<nums.length;i++){          if(nums[i]>nums[i-1]){             ans1=ans2+1;          }else if(nums[i]<nums[i-1]){            ans2=ans1+1;          }      }      return Math.max(ans1,ans2);   }}
+1
ashutoshd20012 months ago
 int end_t=nums[0];
  int flag=1;//1->inc
  int cnt=1;
  for(int i=1;i<n;i++)
  {
      if(flag)
      {
          if(end_t<nums[i])
          {
              cnt++;
              end_t=nums[i];
              flag=!flag;
          }
          else if(end_t>nums[i])
          {
              end_t=nums[i];
          }
      }
      else
      {
          if(end_t>nums[i])
          {
              cnt++;
              end_t=nums[i];
              flag=!flag;
          }
          else if(end_t<nums[i])
          {
              end_t=nums[i];
          }
      }
  }
0
aloksinghbais022 months ago
C++ solution having time complexity as O(N) and space complexity as O(1) is as follows :- 
 
Execution Time :- 0.2 / 1.4 sec
 
int AlternatingaMaxLength(vector<int>&nums){    int n = nums.size();    if(n == 1) return (1);    int ma = 1, mi = 1;    for(int i = 1; i < n; i++){        if(nums[i] > nums[i-1]){            ma = mi + 1;        }        else if(nums[i] < nums[i-1]){            mi = ma + 1;        }    }    return (max(mi,ma));}
 
C++ solution having time complexity as O(N*N) and space complexity as O(N*2) is as follows :- 
 
Getting TLE for this bottom up dp approach.
 
int AlternatingaMaxLength(vector<int>&nums){     int n = nums.size();     if(n == 1) return (1);          int dp[n][2];     for(int i = 0; i < n; i++)         dp[i][0] = dp[i][1] = 1;          int mx = 0;     for(int i = 1; i < n; i++){         for(int j = 0; j < i; j++){             if(nums[j] < nums[i]){                 dp[i][0] = max(dp[i][0],dp[j][1]+1);             }             else if(nums[j] > nums[i]){                 dp[i][1] = max(dp[i][1],dp[j][0]+1);             }         }         mx = max({mx,dp[i][0],dp[i][1]});     }     return (mx); }
0
aniketmukherjee91172 months ago
Approach in DP using 1D array:
class Solution:def AlternatingaMaxLength(self, nums):    if len(nums) == 1:           return 1                  dp = [0]*(len(nums))       dp[0]=1       if nums[1] >= nums[0]:           flag = 'down'       else:           flag = 'up'       for i in range(1,len(nums)):           if nums[i] > nums[i-1] and flag=='down':               dp[i] = dp[i-1]+1               flag = 'up'           elif nums[i] < nums[i-1] and flag=='up':               dp[i]=dp[i-1]+1               flag = 'down'           else:               dp[i] = dp[i-1]                      return dp[-1]
 
0
amanpandey30073 months ago
int AlternatingaMaxLength(vector<int>&nums) {    int n=nums.size();    int d=1,u=1,nd,nu; 
// new down
// new  up    
 
    for(int i=1;i<n;i++)    {        if(nums[i]>nums[i-1])        {            nu=d+1;            nd=d;            u=nu;        }        else if(nums[i]<nums[i-1])        {            nd=u+1;            nu=u;            d=nd;        }            }        return max(u,d); }
+3
gaurabhkumarjha271020015 months ago
int AlternatingaMaxLength(vector<int>&nums){
		    // Code here
		    
		    int n= nums.size();
		    int ma= 1;
		    int mi= 1;
		    
		    
		    for (int i=1; i<n; i++){
		        
		        if (nums[i] > nums[i-1]){
		            
		            ma= mi+1;
		        }
		        
		      else if(nums[i] < nums[i-1]){
		          
		          mi= ma+1;
		      }
		      
		       else
		        continue;
		    }
		    
		    return max (ma, mi);
		}
+8
shivambhadani1236 months ago
int AlternatingaMaxLength(vector<int>&nums){
		    int up = 1, down = 1;
		    for(int i=1; i<nums.size(); i++) {
		        if(nums[i]>nums[i-1]) up = down+1;
		        else if(nums[i]<nums[i-1]) down = up+1; 
		    }
		    return max(down, up);
		}
0
navidulhaque7 months ago
Simple c++ solution TC- O(n) .... SC- O(1)
int AlternatingaMaxLength(vector<int>&nums){
		    // Code here
		    int c=0;
		    int ans=0;
		    int f=0;
		    for(int i=0;i<nums.size()-1;i++){
		        if(nums[i]>nums[i+1]&&f==0){
		            c++;
		            f=1;
		        }
		        else if(nums[i]<nums[i+1]&&f==1){
		            c++;
		            f=0;
		        }
		    }
		    ans=max(ans,c);
		    c=0;
		    f=0;
		    for(int i=0;i<nums.size()-1;i++){
		        if(nums[i]<nums[i+1]&&f==0){
		            c++;
		            f=1;
		        }
		        else if(nums[i]>nums[i+1]&&f==1){
		            c++;
		            f=0;
		        }
		    }
		    ans=max(ans,c);
		    return ans+1;
		}
+4
debdeepsengupta7 months ago
int AlternatingaMaxLength(vector<int>&nums){int in = 1;int d = 1;int n = nums.size();for (int i = 1; i < n; i++) {if (nums[i - 1] < nums[i])in = d + 1;else if (nums[i - 1] > nums[i])d = in + 1;}return max(in, d); } 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.