Maximum length of subarray such that all elements are equal in the subarray
Given an array arr[] of N integers, the task is to find the maximum length subarray that contains similar elements.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 5, 5, 5, 5, 2, 2, 1, 1}
Output: 5
Explanation:
The subarray {5, 5, 5, 5, 5} has maximum length 5 with identical elements.
Input: arr[] = {1, 2, 3, 4}
Output: 1
Explanation:
All identical element subarray are {1}, {2}, {3}, and {4} which is of length 1.
Approach: The idea is to traverse the array store the maximum length and current length of the subarray which has the same elements. Below are the steps:
- Traverse the array and check if the current element is equal to the next element then increase the value of the current length variable.
- Now, compare the current length with max length to update the maximum length of the subarray.
- If the current element is not equal to the next element then reset the length to 1 and continue this for all the elements of the array.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int longest_subarray( int arr[], int d)
{
if (d <= 1) return d;
int i = 0, j = 1, e = 0;
for (i = 0; i < d - 1; i++) {
if (arr[i] == arr[i + 1]) {
j = j + 1;
}
else {
j = 1;
}
if (e < j) {
e = j;
}
}
return e;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << longest_subarray(arr, N);
}
|
Java
import java.util.*;
class GFG {
static int longest_subarray( int arr[], int d)
{
if (d <= 1 )
return d;
int i = 0 , j = 1 , e = 0 ;
for (i = 0 ; i < d - 1 ; i++) {
if (arr[i] == arr[i + 1 ]) {
j = j + 1 ;
}
else {
j = 1 ;
}
if (e < j) {
e = j;
}
}
return e;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int N = arr.length;
System.out.print(longest_subarray(arr, N));
}
}
|
Python3
def longest_subarray(arr, d):
if d < = 1 :
return d
(i, j, e) = ( 0 , 1 , 0 )
for i in range (d - 1 ):
if arr[i] = = arr[i + 1 ]:
j + = 1
else :
j = 1
if e < j:
e = j
return e
arr = [ 1 , 2 , 3 , 4 ]
N = len (arr)
print (longest_subarray(arr, N))
|
C#
using System;
class GFG {
static int longest_subarray( int [] arr, int d)
{
if (d <= 1)
return d;
int i = 0, j = 1, e = 0;
for (i = 0; i < d - 1; i++) {
if (arr[i] == arr[i + 1]) {
j = j + 1;
}
else {
j = 1;
}
if (e < j) {
e = j;
}
}
return e;
}
public static void Main(String[] args)
{
int [] arr = { 1, 2, 3, 4 };
int N = arr.Length;
Console.Write(longest_subarray(arr, N));
}
}
|
Javascript
<script>
function longest_subarray(arr , d)
{
if (d <= 1) return d;
var i = 0, j = 1, e = 0;
for (i = 0; i < d - 1; i++)
{
if (arr[i] == arr[i + 1])
{
j = j + 1;
}
else
{
j = 1;
}
if (e < j) {
e = j;
}
}
return e;
}
var arr = [ 1, 2, 3, 4 ];
var N = arr.length;
document.write(longest_subarray(arr, N));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
18 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...