0

I am given an array of elements and the sum K, and I am supposed to find a subarray (doesn’t have to be contiguous) whose sum is equal to K.

For example: Input: [1, 9, 3, 2, 21], 30 Output: [9, 21]

Do I need to use backtracking or is there another algorithm using dynamic programming for example?

2
  • Welcome to Stack Overflow. Please be aware this is not a code-writing or tutoring service. We can help solve specific, technical problems, not open-ended requests for code or advice. Please edit your question to show what you have tried so far, and what specific problem you need help with. See the How To Ask a Good Question page for details on how to best help us help you. Commented Nov 25, 2021 at 13:26
  • 1
    Have a look at this wikipedia page: en.wikipedia.org/wiki/Subset_sum_problem Commented Nov 25, 2021 at 13:26

2 Answers 2

1

If it's not a big array you could use brute force: 2^n solutions!

Sign up to request clarification or add additional context in comments.

Comments

0

I can provide the solution, using C++.

//Input: [1, 9, 3, 2, 21],
//resultingSum=30,
//Output: [9, 21].
#include <iostream>
#include <vector>
#include <set>
using namespace std;
const int maximumSize=40;
vector<int> visited(maximumSize, 0);
vector<int> numbers={1, 9, 3, 2, 21};
int resultingSum=30;
set<int> resultingSet;
void showContentVector(vector<int>& input)
{
    for(int i=0; i<input.size(); ++i)
    {
        cout<<input[i]<<", ";
    }
}
void showContentSet(set<int>& input)
{
    for(auto iterator=input.begin(); iterator!=input.end(); ++iterator)
    {
        cout<<*iterator<<", ";
    }
    return;
}
void dfs(int current, int previous)
{
    if(visited[current]==1)
    {
        return;
    }
    visited[current]=1;
    for(int next=0; next<numbers.size(); ++next)
    {
        if(next==current)
        {
            continue;
        }
        if((numbers[current]+numbers[next])==resultingSum)
        {
            resultingSet.insert(numbers[current]);
            resultingSet.insert(numbers[next]);
        }
    }
    for(int next=(current+1); next<numbers.size(); ++next)
    {
        if(next==previous)
        {
            continue;
        }
        dfs(next, current);
    }
    return;
}
int main()
{
    dfs(0, -1);
    showContentSet(resultingSet);
    return 0;
}

Here is the result:

9, 21, 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.