Nicholas has an array a that containsn distinct integers from1 to n. In other words, Nicholas has a permutation of sizen.
Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance between the minimum and the maximum elements. The distance between two elements is considered to be equal to the absolute difference between their positions.
The first line of the input contains a single integern (2 ≤ n ≤ 100) — the size of the permutation.
The second line of the input contains n distinct integers a1, a2, ..., an (1 ≤ ai ≤ n), where ai is equal to the element at thei-th position.
Print a single integer — the maximum possible distance between the minimum and the maximum elements Nicholas can achieve by performing exactly one swap.
5 4 5 1 3 2
3
7 1 6 5 3 4 7 2
6
6 6 5 4 3 2 1
5
In the first sample, one may obtain the optimal answer by swapping elements1 and 2.
In the second sample, the minimum and the maximum elements will be located in the opposite ends of the array if we swap7 and 2.
In the third sample, the distance between the minimum and the maximum elements is already maximum possible, so we just perform some unnecessary swap, for example, one can swap5 and 2.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <map>
#include <set>
using namespace std;
int a[100];
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
int maxn = -1, minn = 0x7fffffff, ia = 0, in = 0;
for (int i = 0; i < n; i++) {
if (a[i] > maxn) {
maxn = a[i];
ia = i;
}
if (a[i] < minn) {
minn = a[i];
in = i;
}
}
if (ia == 0 || ia == n - 1 || in == 0 || in == n - 1) {
cout << n - 1 << endl;
} else {
cout << max(max(in, ia), max(n - 1 - in, n - 1 - ia)) << endl;
}
return 0;
}

本文探讨了一个有趣的问题:如何通过一次交换操作使一个包含从1到n的唯一整数的数组中最小值和最大值之间的距离最大化。文章提供了一个算法实现方案,包括输入输出示例及解释。
427

被折叠的 条评论
为什么被折叠?



