本题应尽可能是结果为正数,所以负数应该尽量成对出现
对数组按大到小排序,双指针分别指向数组首尾
分两种情况:
第一种情况k为偶数:比较数组前两个的乘积和后两个乘积,选取较大的乘积,然后指针相应偏移两位。
第二种情况k为奇数:先选取最大的一个数,如果是正数,剩余的就按k为偶数的情况,继续选取;如果是负数,说明最终的结果一定为负数,选取前k个数就可以了
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e5+10;
const int mod = 1e9+9;
int n, k, a[N];
int l, r, ans = 1;
signed main(){
cin >> n >> k;
for(int i = 1; i<=n; i++){
cin >> a[i];
}
sort(a+1, a+n+1, greater<int>());
l = 1;r = n;
if(k%2){
if(a[l]>0) ans = a[l];
else if(a[l]<=0){
for(int i = 1; i<=k; i++){
ans = (ans*a[i])%mod;
}
cout << ans;
return 0;
}
l++;
k--;
}
while(k){
if(a[l]*a[l+1]>a[r]*a[r-1]){
ans = a[l]*a[l+1]%mod*ans%mod;
l += 2;
k -= 2;
}
else{
ans = a[r]*a[r-1]%mod*ans%mod;
r -= 2;
k -= 2;
}
}
cout << ans;
return 0;
}