给定一个由N个元素组成的arr [] ,任务是对所有大小为K的子数组进行计数,该子数组至少有一对,其绝对差可以被K – 1整除。
例子:
Input: arr[] = {1, 5, 3, 2, 17, 18}, K = 4
Output: 3
Explanation:
The three subarrays of size 4 are:
{1, 5, 3, 2}: Pair {5, 2} have difference divisible by 3
{5, 3, 2, 17}: Pairs {5, 2}, {5, 17}, {2, 17} have difference divisible by 3
{3, 2, 17, 18}: Pairs {3, 18}, {2, 17} have difference divisible by 3
Input: arr[] = {1, 2, 3, 4, 5}, K = 5
Output: 1
Explanation:
{1, 2, 3, 4, 5}: Pair {1, 5} is divisble by 4
天真的方法:
解决该问题的最简单方法是遍历所有大小为K的子数组,并检查是否存在任何对可以被K – 1整除的对。
时间复杂度: O(N * K * K)
高效方法:可以使用Pigeonhole原理对上述方法进行优化。请按照以下步骤解决问题:
- 考虑分别标记为0、1、2,…,K-2的K-1框。它们表示将数组中的任何数字x除以K-1时的余数,这意味着这些框存储数组元素的模K-1 。
- 现在,根据Pigeonhole原理,在大小为K的子数组中,必须至少有一对具有相同余数的盒子。这意味着至少有一对其差值或总和将被K整除。
- 根据该定理,我们可以得出结论,每个大小为K的子数组将始终至少有一对,其差可被K-1整除。
- 因此,答案将等于给定数组中可能存在的大小为K的子数组的数量,该数量等于N – K + 1 。
下面是上述方法的实现:
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Function to return the required
// number of subarrays
int findSubarrays(int arr[],
int N,
int K)
{
// Return number of possible
// subarrays of length K
return N - K + 1;
}
// Driver Code
int main()
{
int arr[] = { 1, 5, 3, 2, 17, 18 };
int K = 4;
int N = sizeof(arr) / sizeof(arr[0]);
cout << findSubarrays(arr, N, K);
return 0;
}
Java
// Java implementation of the
// above approach
class GFG{
// Function to return the required
// number of subarrays
static int findSubarrays(int arr[], int N,
int K)
{
// Return number of possible
// subarrays of length K
return N - K + 1;
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 1, 5, 3, 2, 17, 18 };
int K = 4;
int N = arr.length;
System.out.print(findSubarrays(arr, N, K));
}
}
// This code is contributed by shivanisinghss2110
Python3
# Python3 implementation of the
# above approach
# Function to return the required
# number of subarrays
def findSubarrays(arr, N, K):
# Return number of possible
# subarrays of length K
return N - K + 1;
# Driver Code
if __name__ == '__main__':
arr = [ 1, 5, 3, 2, 17, 18 ];
K = 4;
N = len(arr);
print(findSubarrays(arr, N, K));
# This code is contributed by Rohit_ranjan
C#
// C# implementation of the
// above approach
using System;
class GFG{
// Function to return the required
// number of subarrays
static int findSubarrays(int []arr, int N,
int K)
{
// Return number of possible
// subarrays of length K
return N - K + 1;
}
// Driver Code
public static void Main(String[] args)
{
int []arr = { 1, 5, 3, 2, 17, 18 };
int K = 4;
int N = arr.Length;
Console.Write(findSubarrays(arr, N, K));
}
}
// This code is contributed by Amit Katiyar
输出:
3
时间复杂度: O(1)
辅助空间: O(1)