Advertisement
maycod23

Using_Recursion

Jun 20th, 2022
868
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int recursivesum(int currind, int end, int a[])
  4. {
  5.     if (currind == end) return 0;
  6.     int sum = a[currind] + recursivesum(currind + 1, end, a);
  7.     return sum;
  8. }
  9.  
  10. int recursivemax(int currind, int end, int a[])
  11. {
  12.     if (currind == end) return -INT_MAX;
  13.     int mx = max(a[currind], recursivemax(currind + 1, end, a));
  14.     return mx;
  15. }
  16.  
  17.  
  18. int recursivemin(int currind, int end, int a[])
  19. {
  20.     if (currind == end) return INT_MAX;
  21.     int mn = min(a[currind], recursivemin(currind + 1, end, a));
  22.     return mn;
  23. }
  24.  
  25.  
  26.  
  27. void findsum(vector<int>& a, int l, int r, int &sum, int &count, int& ans, int x)
  28. {
  29.  
  30.     if (sum == x)
  31.     {
  32.         ans = min(ans, count);
  33.         return ;
  34.     }
  35.  
  36.     ////base case
  37.     if (l > r) return;
  38.  
  39.     ///////taking the left most element
  40.     sum += a[l]; count++;
  41.     findsum(a, l + 1, r, sum, count, ans, x);
  42.  
  43.     //backtracking step
  44.     sum -= a[l]; count--;
  45.  
  46.     ///////taking the righmost element
  47.     sum += a[r]; count++;
  48.     findsum(a, l, r - 1, sum, count, ans, x);
  49.  
  50.     sum -= a[r]; count--;
  51.     return;
  52. }
  53.  
  54. int main()
  55. {
  56.     int n, x; cin >> n >> x;
  57.     vector<int> a(n + 1);
  58.     for (int i = 1; i <= n; i++) cin >> a[i];
  59.  
  60.  
  61.     // int sum = recursivesum(1, n + 1, a);
  62.     // cout << "Sum-> " << sum << endl;
  63.  
  64.  
  65.     // int mx = recursivemax(1, n + 1, a);
  66.     // cout << "Max-> " << mx << endl;
  67.  
  68.  
  69.     // int mn = recursivemin(1, n + 1, a);
  70.     // cout << "Min-> " << mn << endl;
  71.  
  72.     int sum = 0, count = 0, ans = INT_MAX;
  73.     findsum(a, 1, n, sum, count, ans, x);
  74.  
  75.     if (ans == INT_MAX)
  76.     {
  77.         ///answer is not updated
  78.         cout << "-1" << endl;
  79.     }
  80.     else cout << ans << endl;
  81.  
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement