Leetcode 2144. Minimum Cost of Buying Candies With Discount

该文介绍了两种解决方案,针对给定的带有折扣的糖果成本数组,通过排序后遍历,计算购买糖果的最低总成本。方法一是直接pop操作,方法二是使用for循环,都旨在每三颗糖果中只计算前两颗的成本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Minimum Cost of Buying Candies With Discount

2. Solution

**解析:**Version 1,先对数组排序,从大到小遍历,每三个数,只统计前两个的cost,不足三个,正常计算。

  • Version 1
class Solution:
    def minimumCost(self, cost: List[int]) -> int:
        cost.sort()
        res = 0
        count = 0
        while cost:
            value = cost.pop()
            count += 1
            if count % 3 != 0:
                res += value
        return res

**解析:**Version 2,先对数组排序,从大到小遍历,每三个数,只统计前两个的cost,不足三个,正常计算。

  • Version 2
class Solution:
    def minimumCost(self, cost: List[int]) -> int:
        cost.sort(reverse=True)
        res = 0
        length = len(cost)
        for i in range(length):
            if i % 3 == 2:
                continue
            else:
                res += cost[i]
        return res

Reference

  1. https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值