I came up to an algorithm to solve this problem. however i am not preety sure what excactly is the time complexity of this solution. Is it O(n^3) or O(n^2) .I want to know what is the time complexity of the given function subarraysDivByK? Please help
{
public int subarraysDivByK(int[] A, int K)
{
int n = A.length;
int count = 0;
for(int i=0;i<n;i )
{
for(int j=i;j<n;j )
{
int sumWindow = findSum(A,i,j);
if(sumWindow%K==0)
{
count ;
}
}
}
return count;
}
public int findSum(int[] a, int start, int end)
{
int sum = 0;
for(int i = start;i<=end;i )
{
sum = sum a[i];
}
return sum;
}
}
CodePudding user response:
For some value of i
you'll try all values of j
from i
to n
. And for each j
you'll calculate the sum of j-i
elements. You'll need O(0 1 ... (n-i))=O((n-i)^2) operations for that. So for all possible values of i
you'll need O(n^2 (n-1)^2 ... 2^2 1^2) = O(n^3) operations. Answer: O(n^3).