Longest subarray with all elements same
Given an array arr[] of size N, the task is to find the largest subarray which consists of all equal elements.
Examples:
Input: arr[] = {1, 1, 2, 2, 2, 3, 3};
Output: 3
Explanation:
Longest subarray with equal elements is {2, 2, 2}
Input: arr[] = {1, 1, 2, 2, 2, 3, 3, 3, 3};
Output: 4
Explanation:
Longest subarray with equal elements is {3, 3, 3, 3}
Approach: The idea is to traverse the array and check that the current element is equal to the previous element or not. If yes then increment the length of the longest subarray by 1. Otherwise, the current longest subarray is equal to 1. Also, update the longest subarray with equal elements at each step of the iteration.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int subarray( int arr[], int n)
{
int ans = 1, temp = 1;
for ( int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) {
++temp;
}
else {
ans = max(ans, temp);
temp = 1;
}
}
ans = max(ans, temp);
return ans;
}
int main()
{
int arr[] = { 2, 2, 1, 1,
2, 2, 2, 3, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << subarray(arr, n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int subarray( int arr[], int n)
{
int ans = 1 , temp = 1 ;
for ( int i = 1 ; i < n; i++)
{
if (arr[i] == arr[i - 1 ])
{
++temp;
}
else
{
ans = Math.max(ans, temp);
temp = 1 ;
}
}
ans = Math.max(ans, temp);
return ans;
}
public static void main(String[] args)
{
int arr[] = { 2 , 2 , 1 , 1 , 2 ,
2 , 2 , 3 , 3 };
int n = arr.length;
System.out.print(subarray(arr, n));
}
}
|
Python3
def subarray(arr, n):
ans, temp = 1 , 1
for i in range ( 1 , n):
if arr[i] = = arr[i - 1 ]:
temp = temp + 1
else :
ans = max (ans, temp)
temp = 1
ans = max (ans, temp)
return ans
arr = [ 2 , 2 , 1 , 1 , 2 ,
2 , 2 , 3 , 3 ]
n = len (arr)
print (subarray(arr, n))
|
C#
using System;
class GFG{
static int subarray( int [] arr, int n)
{
int ans = 1, temp = 1;
for ( int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
{
++temp;
}
else
{
ans = Math.Max(ans, temp);
temp = 1;
}
}
ans = Math.Max(ans, temp);
return ans;
}
public static void Main()
{
int [] arr = { 2, 2, 1, 1, 2,
2, 2, 3, 3 };
int n = arr.Length;
Console.Write(subarray(arr, n));
}
}
|
Javascript
<script>
function subarray(arr, n)
{
var ans = 1, temp = 1;
for ( var i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) {
++temp;
}
else {
ans = Math.max(ans, temp);
temp = 1;
}
}
ans = Math.max(ans, temp);
return ans;
}
var arr = [ 2, 2, 1, 1,
2, 2, 2, 3, 3 ];
var n = arr.length;
document.write( subarray(arr, n));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
18 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...