Given an array of size N I need to find the min number of values that will sum up within a min and max range.
E.g.: consider an array[ 1,2,3,4,5 ]. I need to find min number of values from this array whose sum is greater than 5 and less than 8.
Ans: since 1+5 is greater than 5 and less than 8 so the min number of values is 2 hence the answer.
And below is my function which implements the logic.
int void CheckValue()
{
for (i = 0; i <5; i++)
if (a[i] > min && a[i] < max)
return 1;
for (i = 0; i< 4; i++)
for (j = i + 1; j < 5; j++)
if (a[i] + a[j] > min && a[i] + a[j] < max)
return 2;
for (i = 0; i < 3; i++)
for (j = i + 1; j < 4; j++)
for (k = j+1; k < 5; k++)
if (a[i] + a[j] + a[k] > min && a[i] + a[j] + a[k] < max)
return 3;
for (i = 0; i < 2; i++)
for (j = i + 1; j< 3; j++)
for (k = j + 1; k< 4; k++)
for (l = k + 1; l < 5; l++)
if (a[i] + a[j] + a[k] + a[l] > min && a[i] + a[j] + a[k] + a[l] < max)
return 4;
if(a[0]+a[1]+a[2]+a[3]+a[4]>min && a[0]+a[1]+a[2]+a[3]+a[4]<max)
return 5;
return 0;
}
It works fine but the problem is its complexity. Can anyone provide any suggestions to optimize this code further or provide a better logic to implement this.
I would propose the following solution:
Lets say the minimum value of range is minVal and maximum value is maxVal.
Now sort the array.Lets say the length of array is len
Do a binary search for number in array which is just <= maxVal.
Search pass:
I mean if number is at index i then number at index i+1 should be >=maxVal. Lets say the index of this number is currIndex.
If this number is equal to maxVal then do binary search between 0 to currIndex for number
Search Fail:
This mean highest number is array is less than the maxVal. So for this case follow the steps below:
1) Add the largest number in array to the result set.
2)Now start loop from len-1 t0 1. if arr[len-1] + arr[len] is less that maxVal then add arr[len-1] to result set and continue the loop. If arr[len-1] + arr[len] > maxVal then skip and check for arr[len-1] + arr[len].
and so on.