题意:
给你n个数a【n】,求满足 a1+b1=a2+b2=......s的最多对数 。(a1和b1都表示a数组内的数)
题解:因为不能重复使用,对总和进行遍历,再用双指针。
#include <bits/stdc++.h>
using namespace std;
#define memset(a) memset(a, 0, sizeof(a));
typedef long long int ll;
const int N = 50 + 5;
int a[N];int n;
int check(int s)
{
int l = 0, r = n - 1;
int res = 0;
while (l < r)
{
int sum = a[l] + a[r];
if (sum == s)
{
l++;
r--;
res++;
}
else if (sum > s)
r--;
else if (sum < s)
l++;
}
return res;
}
int main()
{
int t;
cin >> t;
while (t--)
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a, a+ n);
int mx = 0;
for (int s = 2; s <= 2 * n; s++)
{
int res = check(s);
mx = max(res, mx);
}
cout << mx << endl;
}
}
|