Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

maximum no. of elements in an array having sum less than or equal to k

Tags:

arrays

max

sum

I want to find the maximum no. of elements in a given positive integer array such that their sum is less than or equal to a given no. k. For example, I have an array

[3,4,7,2,6,5,1] and k=6;

The Answer is 3 as 1,2,3 are maximum elements to give sum 6.

like image 218
Brij Raj Kishore Avatar asked Jun 04 '16 18:06

Brij Raj Kishore


1 Answers

Sort the array, count the number of elements, then start summing elements sequentially until their sum is greater than k or you have gone through each element, then subtract 1 from the count if the sum is greater than k

Pseudocode:

    let k=6
    sort the array
    [1,2,3,4,5,6,7]
    let sum=0
    let count=7 //(7 elements in the array)
    for (i=0;i<7;i++) {
        sum+=array[i];
        if (sum>k)
            break;
    }
    if (sum>k)
    i--;

i is the max number of elements.

like image 197
chiliNUT Avatar answered Sep 30 '22 19:09

chiliNUT