Leetcode 2144. Minimum Cost of Buying Candies With Discount

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

1. Description

Minimum Cost of Buying Candies With Discount

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
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
1
2
3
4
5
6
7
8
9
10
11
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/
如果有收获,可以请我喝杯咖啡!