这里有一个可以使用的方法:
创建一个求和模 k 的数组,例如。
设数组为:{3,4,10,15,1,4,7}
和 k = 5。然后,求和模数组看起来像:
{3,2,2,2,3,2,4} 创建为:{3%5, (3+4)%5, (3+4+10)%5...} 等等。
现在找到最大索引差异 b/w 相似的数字。由于 k
在这种情况下,它可以是:{(4-0 = 4) ->index of 3} 或 {(5-1 = 4) ->index of 2},所以 4。
#include<stdio.h>
int main(){
int n,k,i,j;
scanf("%d%d",&n,&k); //size of the input array 'n' and modular 'k'
int a[n];
for(i = 0;i < n;i++)
scanf("%d",&a[i]);
//actual processing starts
//creating summation modulo array in 'a' itself
a[0] %= k;
for(i = 1;i < n;i++){
a[i] = (a[i-1] + a[i]) % k;
}
int r[2][k];
for(i = 0;i < k;i++)
r[0][i] = r[1][i] = -1; //initializing 'r' to -1
//now evaluating min and max position of any spec no.
for(i = 0;i < n;i++){
if(r[0][a[i]] == -1)
r[0][a[i]] = i;
else
r[1][a[i]] = i;
}
//evaluation of min-max indices complete
int g = 0;
//now find max diff if both values are set
for(i = 0;i < k;i++){
if(r[0][i] != -1 && r[1][i] != -1 && r[1][i] - r[0][i] > g)
g = r[1][i] - r[0][i];
}
printf("%d\n",g); //this is the required answer
}