在我学习面试的时候,我在GeeksForGeeks上找到了这个问题和解决方案,但不明白答案。在
上面说的是Let there be a subarray (i, j) whose sum is divisible by k
sum(i, j) = sum(0, j) - sum(0, i-1)Sum for any subarray can be written as q*k + rem where q is a
quotient and rem is remainder Thus,
^{pr2}$
We see, for sum(i, j) i.e. for sum of any subarray to be
divisible by k, the RHS should also be divisible by k.
(q1 - q2)k is obviously divisible by k, for (rem1-rem2) to
follow the same, rem1 = rem2 where
^{3}$
首先,我不知道q1和{}表示什么。在def subCount(arr, n, k):
# create auxiliary hash
# array to count frequency
# of remainders
mod =[]
for i in range(k + 1):
mod.append(0)
cumSum = 0
for i in range(n):
cumSum = cumSum + arr[i]
mod[((cumSum % k)+k)% k]= mod[((cumSum % k)+k)% k] + 1
result = 0 # Initialize result
# Traverse mod[]
for i in range(k):
if (mod[i] > 1):
result = result + (mod[i]*(mod[i]-1))//2
result = result + mod[0]
return result
在这个解决方案代码中,我没有得到mod的角色。增加第((cumSum % k)+k)% k个数组的数目有什么效果?在
如果能一步一步地解释清楚那就太好了。谢谢。在