fork download
  1. #include<iostream>
  2. #include<cmath>
  3.  
  4. using namespace std;
  5.  
  6.  
  7. void haha(int arr[], int elements, int sum);
  8.  
  9. int target,answer=0;
  10.  
  11. int main(){
  12. int elements;
  13. cout << "Enter the number of elements: ";
  14. cin >> elements;
  15. cout << "Enter the target sum: ";
  16. cin >> target;
  17. cout << "Enter the elements of the array: "<<endl;
  18. int arr[elements];
  19. for(int i=0; i<elements; i++) cin >> arr[i];
  20. haha(arr,elements,0);
  21. cout << "Closest sum to "<<target<<" without exceeding it is: "<<answer;
  22.  
  23. return 0;
  24. }
  25.  
  26.  
  27. void haha(int arr[], int elements, int sum){
  28. if(elements<1){
  29. if(sum > answer && sum <= target) {
  30. answer = sum;
  31. }
  32. }
  33. else{
  34. haha( arr, elements-1, sum);
  35. haha( arr, elements-1, sum+arr[elements-1]);
  36. }
  37.  
  38.  
  39. }
  40.  
Success #stdin #stdout 0s 5284KB
stdin
3 4 1 2 3
stdout
Enter the number of elements: Enter the target sum: Enter the elements of the array: 
Closest sum to 4 without exceeding it is: 4