fork(3) download
  1. /*
  2. skbly7 Solution ( Shivam Khandelwal)
  3. Read more about problem at : http://stackoverflow.com/questions/17349268/selection-of-elements-from-array
  4.  
  5. */
  6.  
  7. #include<stdio.h>
  8. int R[100],TEMP[100],A[100],curSum,minSum,N,M;
  9.  
  10. void print_array(int TEMP[],int l)
  11. {
  12. int i;
  13. printf("Answer recieved :\n");
  14. for(i=0;i<l;i++)
  15. printf("%d ",TEMP[i]);
  16. printf("\n");
  17. }
  18.  
  19. void find_ans(int start,int left)
  20. {
  21. int i;
  22. if(left==0)
  23. {
  24. curSum=0;
  25. for(i=0;i<M;i++)
  26. curSum=curSum+TEMP[i];
  27. if(curSum<minSum&&curSum>0)
  28. {
  29. minSum=curSum;
  30. for(i=0;i<M;i++)
  31. R[i]=TEMP[i];
  32. }
  33. return;
  34. }
  35. for(i=start;i<=(N-left);i++)
  36. {
  37. TEMP[left-1]=A[i];
  38. find_ans(i+1,left-1);
  39. }
  40. }
  41.  
  42. int main()
  43. {
  44. int i;
  45. scanf("%d %d",&N,&M);
  46. minSum=1000000;
  47. for(i=0;i<N;i++)
  48. scanf("%d",&A[i]);
  49. find_ans(0,M);
  50. print_array(R,M);
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0s 1792KB
stdin
12 5 -1000 -700 -400 -200 -100 -50 10 100 300 600 800 1200
stdout
Answer recieved :
800 600 10 -400 -1000