Description
Given an integer array nums
and an integer k
, return the number of non-empty subarrays that have a sum divisible by k
.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
Example 2:
Input: nums = [5], k = 9
Output: 0
Constraints:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
2 <= k <= 104
Code
Brute Force (TLE)
Time Complexity: O(n2), Space Complexity: O(n)
Math
KEY:
if Simodk=Sjmodk
then (Si−Sj)modk=(Simodk−Sjmodk)modk=0modk
類似 Subarray Sum Equals K,code 幾乎一模一樣,只新增了 modulo 的部分。
若在前面有出現兩個 remainder 相同的位置,那新的這個位置就會創造出三段符合條件的 subarray。
因為上面的公式用到 modulo operation,所以要注意負數的計算
Ex: [-1, -4, 5, 5], k = 2
Source