Two arrays:NC[],NP[]
Supposed that two points (l1 and r1)start from the head and the tail of the array of NC seperately,in a similar way,exists two points(l2 and r2)points to the the head and end of the array of NP.
l1 and l2 move to the right step by step guaranted that nc[l1]<0 and np[l2]<0,otherwise terminate.certainly we compute the product:NC[l1]*NC[l2] every step.
r1 and r2 move to the right step by step guaranted that nc[r1]>0 and np[r2]>0,otherwise terminate.certainly we compute the product:NC[r1]*NC[r2]
every step.
// 1037. Magic Coupon.cpp: 主项目文件。 #include "stdafx.h" #include <cstdio> #include <algorithm> using std::sort; const int N=100003; int nc[N],np[N]; int ncNum,npNum; int maxProfit(){ int l1=0,r1=ncNum-1,l2=0,r2=npNum-1; int profitSum=0; sort(nc,nc+ncNum); sort(np,np+npNum); while(l1<ncNum&&l2<npNum&&nc[l1]<0&&np[l2]<0) profitSum+=nc[l1]*np[l2],l1++,l2++; while(r1>=0&&r2>=0&&nc[r2]>0&&np[r2]>0) profitSum+=nc[r1]*np[r2],r1--,r2--; return profitSum; } int main() { scanf("%d",&ncNum); for(int i=0;i<ncNum;i++) scanf("%d",nc+i); scanf("%d",&npNum); for(int i=0;i<npNum;i++) scanf("%d",np+i); int res=maxProfit(); printf("%d\n",res); return 0; }