使用 C++ 查找任意两个不同数字索引之间最大差值的程序
本问题中,我们得到一个包含 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP