이 문제에서는 n개의 정수로 구성된 배열 arr[]이 제공됩니다. 우리의 임무는 C++에서 서로 다른 두 숫자의 인덱스 간의 최대 차이를 찾는 프로그램을 만드는 것입니다.
코드 설명 − 여기서 두 정수가 다른 경우 배열의 정수 값 인덱스 간의 최대 차이를 찾아야 합니다.
문제를 이해하기 위해 예를 들어보겠습니다.
입력
arr[] = {4, 1, 3, 2, 1, 2, 4} 출력
5
설명
인덱스 0, 요소 4와 인덱스 5, 요소 2의 차이.
해결 방법
배열에서 고유한 요소의 인덱스 간의 가능한 최대 차이를 찾으려고 노력할 것입니다.
우리 솔루션의 구현을 보여주는 프로그램
예
#include <iostream>
using namespace std;
int maximum(int a, int b){
if(a > b)
return a;
return b;
}
int CalcMaxIndDiff(int a[], int n) {
int indDiff1 = 0, indDiff2 = 0;
int i = 0;
while(i < (n - 1)){
if(a[0] != a[i]){
indDiff2 = i;
break;
}
i++;
}
i = (n - 1) ;
while(i > 0){
if(a[0] != a[i]){
indDiff1 = i;
break;
}
i--;
}
return maximum(indDiff1, indDiff2);
}
int main() {
int arr[] = { 4, 1, 3, 2, 1, 2, 4 };
int n = 7;
cout<<"The maximum difference between the index of any two different numbers is "<<CalcMaxIndDiff(arr, n);
return 0;
} 출력
The maximum difference between the index of any two different numbers is 5