Longest subarray with all elements same | C ++ program to find largest subarray with all equal elements . ; Function to find largest sub array with all equal elements . ; Traverse the array ; If element is same as previous increment temp value ; Return the required answer ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE 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 ; }