Sum of Numbers

Given an array of N elements, check if it is possible to obtain a sum of S, by choosing some (or none) elements of the array and adding them.

Example:

Input:  n = 5, arr[n] = {3, 2, 0, 7, -1}, sum = 8
Output: YES

Approach

C++

#include <bits/stdc++.h>
using namespace std;

void sumOfNumbers(long long n,
                  long long arr[], long long sum)
{
    if (sum == 0)
        cout << "YES\n";
    else
    {
        int flag = 0;
        for (long long i = 0i <= 1 << ni++)
        {
            long long ans = 0;
            for (long long j = 0j < nj++)
            {
                if (i & 1 << j)
                    ans += arr[j];
            }
            if (ans == sum)
            {
                flag = 1;
                break;
            }
        }
        if (flag == 1)
            cout << "YES\n";
        else
            cout << "NO\n";
    }
}
int main()
{

    long long n = 5;
    long long arr[n] = {3207, -1};

    long long sum = 8;

    sumOfNumbers(narrsum);

    return 0;
}


No comments:

Post a Comment