使用 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