题目描述
一个数组中有若干个数,数字可能有重复。从中选出尽可能多的数,这些数两两之间的距离可以被M整除,求这种数的最大值
例如, A [ 0 ] = − 3 , A [ 1 ] = − 2 , A [ 2 ] = 1 , A [ 3 ] = 0 , A [ 4 ] = 8 , A [ 5 ] = 7 , A [ 6 ] = 1 A[0] = -3, A[1] = -2, A[2] = 1, A[3] = 0, A[4] = 8, A[5] = 7, A[6] = 1 A[0]=−3,A[1]=−2,A[2]=1,A[3]=0,A[4]=8,A[5]=7,A[6]=1,那么 A [ 1 ] , A [ 2 ] , A [ 5 ] , A [ 6 ] A[1], A[2], A[5], A[6] A[1],A[2],A[5],A[6]两两之间就可以被3整除,最大值就为4
求模M同余的最大数
int find(vector<int> A, int M) {
int res = 0;
int n = A.size();
map<int, int> m;
for (auto &t : A) {
if (t < 0) {
while (t < 0) t += M;
} else t = t % M;
m[t]++;
res = max(res, m[t]);
}
return res;
}