Given an infinite positive integer array or say a stream of positive integers, find out the first five numbers whose sum is twenty.
After reading the problem statement, it at first seems like a problem 0-1 Knapsack, but I'm confused about what can be used 0-1 Knapsack algofor a stream of integers. Suppose I am writing a recursive program for the indicated problem.
int knapsack(int sum, int count, int idx)
{
if (sum == 0 && count == 0)
return 1;
if ((sum == 0 && count != 0) || (sum != 0 && count == 0))
return 0;
if (arr[idx] > 20)
return knapsack(sum, count idx + 1);
return max(knapsack(sum, count, idx +1), knapsack(sum - arr[idx], count -1, idx + 1));
}
Now that the above function will call an infinite array, the first call to the maxie function knapsack(sum, count, idx +1)will never return, as it will continue to ignore the current element. Even if we change the order of the call in the function max, there is a chance that the first call will never return. Is there any way to apply knapsackalgo in such scenarios?
source
share