Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a combination of K integers exist, so that their sum is equal to a given number?

I've been breaking a sweat over this question I've been asked to answer (it's technically homework). I've considered a hashtable but I'm kind of stuck on the exact specifics of how I'd make this work

Here's the question:

Given k sets of integers A1,A2,..,Ak of total size O(n), you should determine whether exist a1 ϵ A1, a2 ϵ A2,..,ak ϵ Ak, such that a1+a2+..+ak−1 =ak. Your algorithm should run in Tk(n) time, where Tk(n) = O(nk/2 × log n) for even k, and O(n(k+1)/2) for odd values of k.

Can anyone give me a general direction so that I can come closer to solving this?

like image 542
Arnon Avatar asked Dec 17 '11 15:12

Arnon


People also ask

How do you find all pairs of an integer array whose sum is equal to a given number in JS?

function arraypair(array,sum){ for (i = 0;i < array. length;i++) { var first = array[i]; for (j = i + 1;j < array. length;j++) { var second = array[j]; if ((first + second) == sum) { alert('First: ' + first + ' Second ' + second + ' SUM ' + sum); console.


1 Answers

Divide the k sets into two groups. For even k, both groups have k/2 sets each. For odd k, one group has (k+1)/2 and the other has (k-1)/2 sets. Compute all possible sums (taking one element from each set) within each group. For even k, you will get two arrays, each with nk/2 elements. For odd k, one array has n(k+1)/2 and the other array has n(k-1)/2 elements. The problem is reduced to the standard one "Given two arrays, check if a specified sum can be reached by taking one element from each array".

like image 165
viswanathgs Avatar answered Sep 23 '22 04:09

viswanathgs