Search code examples
arrayssummax

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


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.


Solution

  • 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.