Credit Suisse Interview Question
AnalystsCountry: India
Interview Type: Written Test
If you can get a single number equal to exactly the sum in the array and that should not be counted then yes, {15, 5, 3, 2} with sum 15 is a fail. However it would be easy to code around, e.g. add a "first_call" parameter to sumCountHelper; if total == 0 && first_call then return without incrementing count. If we get to the recursive call then call sumCountHelper with first_call = false.
Apply the subset algorithm -- iterate from 1 to (2^(array size) - 1). Use binary representation of i to select numbers that have 1 at corresponding position. Get sum of it. If it's equals to sought, output/count.
int sumcount(int *arr,int len,int total)
{
int count=0,i,j;
int tot;
for(i=0;i<len;i++)
{
tot=total-arr[i];
for(j=i+1;j<len;j++)
{
tot=tot-arr[j];
if(tot==0)
{
count++;
tot=tot+arr[j];
}
if(tot<0)
break;
}
}
return count;
}
- pranaymahajan August 27, 2012