题解 | 支付宝消费打折

支付宝消费打折

https://www.nowcoder.com/practice/f8997c9b82714f058e12433a32614993

const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;

void async function () {
    // let n = 0;//n种物品
    let k = 0;//支付宝余额k元
    let col = 0;//输入行数
    let list = []
    while (line = await readline()) {
        let tokens = line.split(' ');
        if (col === 0) {
            n = parseInt(tokens[0]);
            k = parseInt(tokens[1]);
        } else if (col === 1) {
            // n种物品的价格
            for (let i = 0; i < tokens.length; i++) {
                list.push({  price: parseInt(tokens[i]) })
            }

        } else {
            // n种物品是否支持优惠及实际价格 支持优惠1=九五折
            tokens = line.split('');
            for (let i = 0; i < tokens.length; i++) {
                let item = list[i]
                if(parseInt(tokens[i])===1){
                    item.price = parseFloat(item.price * 0.95.toFixed(2))
                }
            }
        }
        col++;
    }
    // 贪心逻辑分析:要买到最多的物品,那么就要选最低的价格
    // 进行实际价格的升序排列
    list.sort((a, b) => {
        return a.price - b.price
    })

    // 选出总价格小于k的物品
    let sum = 0;//总价格
    let count = 0; //符合条件的物品计数
    list.forEach(item => {
        if (sum + item.price > k) {
            return
        }
        sum += item.price;
        count++;
    })
    console.log(count)
}()

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务