Dec 25, 2008

void groupThatEquals( int total, int groupSize, int[] numbers )

void groupThatEquals( int total, int groupSize, int[] numbers )
This is a prototype of the function where number is given an array of ints, total is given as a number and groupsize is also given as parameter.
For example, an array of numbers is 3,4,16,2,13,8,5,7,2,9
Suppose Total= 28, groupSize = 3
So we have to come up with a group size of 3 in this example whose sum will be equal to 28. In this case it is 3,16 and 9 which makes total = 28. Array is not sorted and number need not be contiguous.
We have to find all possible groups that sum to Total.
Suppose the groupsize is 3

First, sort the array, takes O(nlogn).
Then, iteratively take one from highest to lowest, to find the rest two number use hashtable, check if A[sum-A[n]-A[i]] exist, and only half of the array need to be checked, because the search is always symmetrical. O(n^2)
Or sort the array, take one num, then use two pointers, one of which p1 point to start(p1++), the other one p2 point to end(p2--), search for a[p1]+a[p2]=sum-numm
This is 3 sum problem, low bound is O(n^2)

foo(int A[], int len, int sum)
{
for(int i=0;i < len;i++)
{
int j=i+1;
int k=len-1;
while(j < k)
{
if(A[j]+A[k] < sum-A[i]) j++;
else if(A[j]+A[k]>sum-A[i]) k--;
else {print; j++;k--;}
}
}
}

No comments:

Post a Comment