There is no maximum. elements in an array having a sum less than or equal to k

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

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

The answer is 3, since 1,2,3 are the maximum elements to get the sum of 6.

+4
source share
2 answers

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

pseudo code:

    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 - maximum number of elements.

+3
source

"Swifty" :

var maxSum = 6
var newSum = 0

let maxElements = [3,4,7,2,6,5,1].sort().filter() {
       if $0 + newSum <= maxSum {
          newSum += $0
          return true
       }
       return false
    } .count    //returns 3
+1

All Articles