Given an array of size N i need to find sum of min numbers of the array which fall within a range.

For eg: consider an array[ 1,2,3,4,5 ].i need to find sum of min numbersfrom this array which is greater than 5 and less than 8.

Ans: since 1+5 is greater than 5 and less than 8 so the output is 2

The way i solved the problem is this way.I checked if min number needed is 1 by using a for loop

Code:

for (i = 0; i < 5; i++)
if (a[i] >= min && a[i] <= max)
return 1;

Then for checking if 2 is the min number

Code:

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;

And so on...

Code:

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;

Code:

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;

And finally ...

Code:

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;

Can any one suggest a more optimised way of solving this problem..