We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
solution using C with recursion function. What I did here is to try to get every possible combination in an optimal way because there is no other way to know the highest possible sum because there are no limits on the numbers used to get this sum.
So for each element in the array, start from the first index and get the maximum sum using it. Store this sum, and each time, reduce this sum by the value in the specific index. and pass this sum to the next index. and do it recursively for all indexes.
for main function issues, just do a for loop t times from char** first_multiple_input = split_string(rtrim(readline())); until fprintf(fptr, "%d\n", result);
the code :
intcumulative_sum(int*arr,intarr_count,intk,intindex,intsum){if(index==arr_count){returnsum;}elseif(k%arr[index]==0){returnk;}intmax_sum=0,temp=0,count=0,i=0;while(sum<=k){sum+=arr[index];count++;}sum-=arr[index];max_sum=sum;for(i=0;i<count;i++){temp=cumulative_sum(arr,arr_count,k,index+1,sum);if(temp==k){returnk;}elseif(temp>max_sum){max_sum=temp;}sum-=arr[index];}returnmax_sum;}/* * Complete the 'unboundedKnapsack' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. INTEGER k * 2. INTEGER_ARRAY arr */intunboundedKnapsack(intk,intarr_count,int*arr){returncumulative_sum(arr,arr_count,k,0,0);}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Knapsack
You are viewing a single comment's thread. Return to all comments →
solution using C with recursion function. What I did here is to try to get every possible combination in an optimal way because there is no other way to know the highest possible sum because there are no limits on the numbers used to get this sum. So for each element in the array, start from the first index and get the maximum sum using it. Store this sum, and each time, reduce this sum by the value in the specific index. and pass this sum to the next index. and do it recursively for all indexes.
for main function issues, just do a for loop t times from
char** first_multiple_input = split_string(rtrim(readline()));
untilfprintf(fptr, "%d\n", result);
the code :