MCPcopy Create free account
hub / github.com/Rohit91singh9/Coding-DP-DSA / bestCombos

Class bestCombos

bestCombos.java:4–61  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

2
3import java.util.*;
4class bestCombos {
5 public static void main(String args[])
6 {
7 Scanner sc=new Scanner(System.in);
8
9 int n=sc.nextInt();
10
11 int popularity[]=new int[n];
12 //input the array
13 for(int i=0;i<n;i++)
14 popularity[i]=sc.nextInt();
15
16 int k=sc.nextInt();
17
18 int combo[]=bestCombo(popularity,k);
19
20 for(int i=0;i<combo.length;i++)
21 System.out.println(combo[i]);
22
23 }
24
25 public static int[] bestCombo(int popularity[],int k)
26 {
27 ArrayList<Integer> combo=new ArrayList<Integer>();
28 int sum=0;
29 combo.add(0);
30 //compute all the combinations
31 for(long i=1;i<Math.pow(2,popularity.length);i++)
32 {
33 sum=0;
34 for(int j=0;j<popularity.length;j++)
35 {
36 if((i&(long)Math.pow(2,j))>0)
37 {
38 sum+=popularity[j];
39 }
40 }
41 combo.add(sum);
42 }
43
44 //sort the list
45 Collections.sort(combo);
46
47 //create the final output array
48 int output[]=new int[k];
49
50 int index=0;
51
52 for(int i=combo.size()-1;i>=0;i--)
53 {
54 output[index++]=combo.get(i);
55 if(index==k)
56 break;
57 }
58
59 return output;
60 }
61}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected