The exact question that I am solving is given here: Codechef - MARCHA1
Problem Statement
Basically, we have an array of n integers, say {1, 5, 6, 3, 12} where n = 5.
Then we have a given number m = 10, and we have to check if the sum of any subset of the array is equal to m or not.
In this case, we have 1+6+3 = 10, so we print Yes.
Proposed Solution
I proposed the following solution:
We create another array of n integers which only hold either 0 or 1. For example, in the case with n = 5, we can have this new array as {0, 0, 0, 0, 1}, {0, 0, 0, 1, 0} .. etc
In this manner, each time we check for the sum of numbers of original array which are at position 1. So there are 2^n such cases.
After checking, if none of them match, we print No, else we print Yes.
Here's the code in C:
#include <stdio.h>
int main()
{
unsigned int n, m;
scanf("%u%u", &n, &m);
unsigned int note[n];
unsigned long j;
for (j = 0; j < n; ++j) {
scanf("%u", note+j);
}
char teller[n], flag = 0;
for (j = 0; j < n; ++j) {
teller[j] = 0;
}
unsigned long two_pow_n = 1 << n;
for (j = 0; j < two_pow_n; ++j)
{
unsigned int sum0 = 0, sum1 = 0, k;
for (k = 0; k < n; ++k)
{
if (teller[k] == 0) {
sum0 += note[k];
}
else {
sum1 += note[k];
}
if (j % (1 << k) == 0) {
teller[k] = teller[k] == 0 ? 1 : 0;// swap 0 and 1
}
}
if (sum0 == m || sum1 == m)
{
flag = 1;
break;
}
}
flag ? printf("Yes\n") : printf("No\n");
return 0;
}
The problem with this approach is that it took too much time and too many comparisons. On the codechef website, I found my solution was among the slowest.
Please help me by suggesting a better algorithm, I couldn't think of any optimisation either. Thank you!
O(2^n)
which makes it unusable for large calculations. On Codechef, you can look at other's solutions, so I suggest have a look at some others like this one: codechef.com/viewsolution/990854. \$\endgroup\$