Longest Continuous Increasing Subsequence in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of integers; we have to find the length of longest continuous increasing subarray.

So, if the input is like [2,4,6,5,8], then the output will be 3. As the longest continuous increasing subsequence is [2,4,6], and its length is 3.

To solve this, we will follow these steps −

  • if size of nums <= 1, then −
    • return size of nums
  • answer := 1, count := 1
  • for initialize i := 0, when i < size of nums, update (increase i by 1), do −
    • if nums[i] < nums[i + 1], then −
      • (increase count by 1)
      • answer := maximum of answer and count
    • Otherwise
      • count := 1
  • return answer

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int findLengthOfLCIS(vector<int>& nums) {
      if (nums.size() <= 1)
         return nums.size();
      int answer = 1, count = 1;
      for (int i = 0; i < nums.size() - 1; i++) {
         if (nums[i] < nums[i + 1]) {
            count++;
            answer = max(answer, count);
         }
         else {
            count = 1;
         }
      }
      return answer;
   }
};
main(){
   Solution ob;
   vector<int> v = {2,4,6,5,8};
   cout << (ob.findLengthOfLCIS(v));
}

Input

{2,4,6,5,8}

Output

3
raja
Published on 04-Jul-2020 09:33:59
Advertisements