在C ++中最大化(arr [i] – i)–(arr [j] – j)的值
问题陈述
给定一个数组,arr []找到(arr [i] – i)–(arr [j] – j)的最大值,其中i不等于j。其中i和j从0到n-1变化,并且n是输入数组arr []的大小。
如果输入数组为{7,5,10,2,3},那么我们可以获得9个最大值,如下所示:
(element 10 – index 2) - (element 2 – index 3)(10 – 2) – (2 – 3) = 8 – (-1) = 9
算法
1. Find maximum value of (arr[i] – i) in whole array.2. Find minimum value of (arr[i] – i) in whole array.
3. Return difference of above two values
示例
#include <bits/stdc++.h>using namespace std;
int getMaxDiff(int *arr, int n){
if (n < 2) {
cout << "Invalid input" << endl;
exit(1);
}
int minVal = INT_MAX;
int maxVal = INT_MIN;
for (int i = 0; i < n; ++i) {
int result = arr[i] - i;
if (result > maxVal) {
cout << "Max = " << arr[i] << " - " << i << endl;
maxVal = result;
}
if (result < minVal) {
cout << "Min = " << arr[i] << " - " << i << endl;
minVal = result;
}
}
return (maxVal - minVal);
}
int main(){
int arr[] = {7, 5, 10, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Maximum value = " << getMaxDiff(arr, n) << endl;
return 0;
}
输出结果
当您编译并执行上述程序时。它生成以下输出-
Maximum value = Max = 7 - 0Min = 7 - 0
Min = 5 - 1
Max = 10 - 2
Min = 2 - 3 9
以上是 在C ++中最大化(arr [i] – i)–(arr [j] – j)的值 的全部内容, 来源链接: utcz.com/z/348834.html