Find the length of Longest increasing Consecutive Subarray
Given an array arr[] of N integers, the task is to find the length of the longest increasing subarray such that elements in the subarray are consecutive integers.
Examples:
Input: arr[] = {1, 9, 3, 4, 20, 2}
Output: 2
Explanation: The subarray {3, 4} is the longest subarray of consecutive elements
Input: arr[] = {36, 41, 56, 32, 33, 34, 35, 43, 32, 42}
Output: 4
Explanation: The subarray {32, 33, 34, 35} is the longest subarray of consecutive elements
Approach: The idea is to run a loop and keep a count and max (both initially zero). Follow the steps mentioned below:
- Run a loop from start to end.
- If the current element is not equal to the (previous element+1) then set the count to 1.
- Else increase the count.
- Update max with a maximum of count and max.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findLongestConseqSubarr(vector< int >& v)
{
int ans = 0, count = 0;
for ( int i = 0; i < v.size(); i++) {
if (i > 0 && v[i] == v[i - 1] + 1)
count++;
else
count = 1;
ans = max(ans, count);
}
return ans;
}
int main()
{
vector< int > arr = { 1, 9, 3, 4, 20, 2 };
cout << findLongestConseqSubarr(arr);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static int findLongestConseqSubarr( int arr[ ])
{
int ans = 0 , count = 0 ;
for ( int i = 0 ; i < arr.length; i++) {
if (i > 0 && arr[i] == arr[i - 1 ] + 1 )
count++;
else
count = 1 ;
ans = Math.max(ans, count);
}
return ans;
}
public static void main (String[] args) {
int arr[ ] = { 1 , 9 , 3 , 4 , 20 , 2 };
System.out.print(findLongestConseqSubarr(arr));
}
}
|
Python3
def findLongestConseqSubarr(v):
ans, count = 0 , 0
for i in range ( 0 , len (v)):
if (i > 0 and v[i] = = v[i - 1 ] + 1 ):
count + = 1
else :
count = 1
ans = max (ans, count)
return ans
if __name__ = = "__main__" :
arr = [ 1 , 9 , 3 , 4 , 20 , 2 ]
print (findLongestConseqSubarr(arr))
|
C#
using System;
class GFG
{
static int findLongestConseqSubarr( int [] arr)
{
int ans = 0, count = 0;
for ( int i = 0; i < arr.Length; i++)
{
if (i > 0 && arr[i] == arr[i - 1] + 1)
count++;
else
count = 1;
ans = Math.Max(ans, count);
}
return ans;
}
public static void Main()
{
int [] arr = { 1, 9, 3, 4, 20, 2 };
Console.Write(findLongestConseqSubarr(arr));
}
}
|
Javascript
<script>
function findLongestConseqSubarr(v)
{
let ans = 0, count = 0;
for (let i = 0; i < v.length; i++) {
if (i > 0 && v[i] == v[i - 1] + 1)
count++;
else
count = 1;
ans = Math.max(ans, count);
}
return ans;
}
let arr = [1, 9, 3, 4, 20, 2];
document.write(findLongestConseqSubarr(arr));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
01 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...