In this HackerEarth Mathison and the funny subarray problem solution Mathison has been playing quite a lot with some array A of length N. A subarray of the given array is called funny if it starts and ends with the same number.

Your task is to find the length of the longest funny subarray of the given array.

HackerEarth Mathison and the funny subarray problem solution

HackerEarth Mathison and the funny subarray problem solution.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>

using namespace std;

int main(){

int N;
cin >> N;

vector<int> A(N);
for (int &x: A)
cin >> x;

map<int, vector<int>> mp;
for (int i = 0; i < N; i++)

int best = 0;

for (auto p: mp){
if (!p.second.empty())
best = max(best, p.second.back() - p.second[0] + 1);

cout << best << endl;

return 0;

Second solution

import java.util.*;
import java.math.*;
import java.util.concurrent.*;

public final class a
static BufferedReader br=new BufferedReader(new InputStreamReader(;
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int maxn=(int)(1e5+5);

public static void main(String args[]) throws Exception
int n=sc.nextInt();int[] a=new int[n],first=new int[maxn],last=new int[maxn];


if(n<1 || n>1000000)
throw new Exception("Wrong!");

for(int i=0;i<n;i++)

if(a[i]<1 || a[i]>100000)
throw new Exception("Wrong!");



int max=0;

for(int i=0;i<maxn;i++)

class FastScanner
BufferedReader in;
StringTokenizer st;

public FastScanner(BufferedReader in) { = in;

public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
return st.nextToken();

public String next() throws Exception {
return nextToken().toString();

public int nextInt() throws Exception {
return Integer.parseInt(nextToken());

public long nextLong() throws Exception {
return Long.parseLong(nextToken());

public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());