I have written a code to find Sum of product of all possible subsets of array. I'm getting the expected output but I'm not able to make it fast enough to clear time related test cases.
Can anyone help me in optimizing my code for speed?
First input (testCases) is the number of testcases. Depending on number of testcase, we will have size of array (size) and array elements (set).
For example, a valid input would be:
1
3
2 3 5
where:
1
is the number of testcases.3
is the size of the test set and2 3 5
are the elements of the input set.
The expected output is:
71
The calculation for the above output is:
{2}, {3}, {5}, {2, 3}, {3, 5}, {2, 5}, {2, 3, 5}
=> 2 3 5 6 15 10 30
=> 2 + 3 + 5 + 6 + 15 + 10 + 30
=> 71
import java.util.Scanner;
public class Test {
static int printSubsets(int set[]) {
int n = set.length;
int b = 0;
for (int i = 0; i < (1 << n); i++) {
int a = 1;
for (int j = 0; j < n; j++){
if ((i & (1 << j)) > 0) {
a *= set[j];
}}
b += a;
}
return b;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int testCases = scanner.nextInt();
for (int i = 0; i < testCases; i++) {
int size = scanner.nextInt();
int set[] = new int[size];
for (int j = 0; j < set.length; j++) {
set[j] = scanner.nextInt();
}
int c = printSubsets(set);
System.out.println((c - 1));
}
scanner.close();
}
}
(2 * 3) + (2 * 5) + (2 * 3 * 5) + (3 * 5) = 61
. – Woodcut2 + 3 + 5
to61
. So you get71
. – Emlyn