给定一个大小为N的整数数组。该数组由随机顺序的整数组成。任务是找到数组中元素的第一个索引与最后一个索引之间的最大差。我们必须找到一个在数组中出现两次的数字,其索引之间的差异最大。如果存在更多这样的对,那么我们将存储索引之间的最大此类差异。
输入值
Arr[] = { 2,1,3,1,3,2,5,5 }.输出-数组中元素的第一个索引与最后一个索引之间的最大差-5
说明-成对的元素及其索引之间的差异如下-
(2,2) Arr[0] and Arr[5] 5-0=5 max difference till now is 5 (1,1) Arr[1] and Arr[3] 3-1=2 max difference till now is 5 (3,3) Arr[2] and Arr[4] 4-2=2 max difference till now is 5 (5,5) Arr[6] and Arr[7] 7-6=1 max difference till now is 5
输入值
Arr[] = { 2,2,3,4,8,3,4,4,8,7 }.输出-数组中元素的第一个索引与最后一个索引之间的最大差-4
说明-成对的元素及其索引之间的差异如下-
(2,2) Arr[0] and Arr[1] ; 1-0=1; max difference till now is 1 (3,3) Arr[2] and Arr[5] ; 5-2=3; max difference till now is 3 (4,4,4) Arr[3],Arr[6],Arr[7] ; 7-6=1,6-3=3,7-3=4; max difference till now is 4 (8,8) Arr[4] and Arr[8] ; 8-4=4 ; max difference till now is 4
声明一个整数数组,其中包含以随机顺序重复的数字。(Arr [])
创建一个变量来存储数组的大小。(N)
函数maxDifference(int Arr [],int n)用于计算数组中元素的第一个索引与最后一个索引之间的最大差(maxD)。
在内部,maxDifference()我们声明了maxD用于存储迄今为止发现的最大索引差。
从第一个元素(索引i = 0)开始,使用for循环遍历数组。
在嵌套for循环中,遍历其余数组(j = i + 1),直到到达最后一个索引。
如果找到与Arr [i]相同的元素,我们将计算其索引i,j之间的差,如果它大于maxD的先前值,则将更新maxD。
继续此操作,直到两个for循环结束。
返回存储在maxD中的结果。
#include <stdio.h>
int maxDifference(int arr[],int n){
int maxD=0;
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(arr[i]==arr[j] && (j-i)>maxD)
maxD=j-i;
}
}
return maxD;
}
int main(){
int Arr[] = {1, 4, 1, 3, 3, 5, 4, 5, 2};
int N = sizeof(Arr) / sizeof(Arr[0]);
printf("Maximum difference between first and last indexes of an element in array : %d" ,maxDifference(Arr, N);
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Maximum difference between first and last indexes of an element in array : 5