ITGUY33 - Editorial

Problem: Contest Page | CodeChef

DIFFICULTY:

EASY.

PROBLEM:

The chef is playing a game of long distance. Chef has a number K and he wants to find the longest distance between the index of the first and the last occurrence of K in a given array of N numbers.

Program:

#include<bits/stdc++.h>
using namespace std;
int main()
 {
	//code
	ios_base::sync_with_stdio(false);
   	cin.tie(NULL);
   	cout.tie(NULL);
   	int t;
   	cin>>t;
   	while(t--){
   		int n,k;
   		cin>>k>>n;
   		int arr[n];
   		for(int i=0;i<n;i++)cin>>arr[i];
   		int f=-1,l=-1;
   		for(int i=0;i<n;i++){
   			if(arr[i]==k){
   				if(f==-1){
   					f=i;
   				}
   				else l=i;
   			}
   		}
   		if(l==-1)cout<<0<<"\n";
   		else cout<<l-f<<"\n";
   	}

}
1 Like

Problem statement asks to print -1 if k is not present. But it was not the intended solution. I kept banging by head for 20 minutes thinking where am I going wrong : .

2 Likes