最大数量数组中总和小于或等于 k ​​的元素 [英] maximum no. of elements in an array having sum less than or equal to k

查看:55
本文介绍了最大数量数组中总和小于或等于 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;

答案是 3,因为 1,2,3 是求和 6 的最大元素.

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

推荐答案

对数组进行排序,计算元素的数量,然后开始按顺序对元素求和,直到它们的总和大于 k 或者您已经遍历了每个元素,然后减去 1如果总和大于 k

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

伪代码:

    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 是元素的最大数量.

这篇关于最大数量数组中总和小于或等于 k ​​的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆