在本教程中,我们将讨论一个程序,以查找数组中最小和第二最小的最大和。
为此,我们将提供一个包含整数的数组。我们的任务是在数组的每个可能迭代中找到最小和第二个最小元素的最大和。
#include <bits/stdc++.h> using namespace std; //返回最大值的最小值和 //第二小元素 int pairWithMaxSum(int arr[], int N) { if (N < 2) return -1; int res = arr[0] + arr[1]; for (int i=1; i<N-1; i++) res = max(res, arr[i] + arr[i+1]); return res; } int main() { int arr[] = {4, 3, 1, 5, 6}; int N = sizeof(arr) / sizeof(int); cout << pairWithMaxSum(arr, N) << endl; return 0; }
输出结果
11