我正在尝试解决这个问题:
http://www.hackerrank.com/challenges/mark-and-toys
由于某些原因,我无法使用当前的解决方案获得正确的预期输出。
预期输出:
He can buy items that cost [1, 5, 10, 12] for 28
The maximum is 4 items当前输出:
He can buy items that cost [1, 5, 10, 12, 111] for 139
The maximum is 5 items我目前的解决方案是:
prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50
def maximumToys(prices, k):
sortedPrices = sorted(prices)
total = 0
toys = []
for i in range(len(sortedPrices)):
if total <= k:
total += sortedPrices[i]
toys.append(sortedPrices[i])
else:
break
print(f"He can buy items that cost {toys} for {total}")
print(f"The maximum is {len(toys)} items")
print(maximumToys(prices, k))发布于 2021-02-17 15:35:44
您的if语句现在只确定您是否低于总金额,然后添加下一项。然而,你应该检查你是否添加了下一个项目,如果你仍然低于你拥有的总金额。我只更改了if语句:
prices = [1, 12, 5, 111, 200, 1000, 10]
k = 50
def maximumToys(prices, k):
sortedPrices = sorted(prices)
total = 0
toys = []
for i in range(len(sortedPrices)):
if total+sortedPrices[i] <= k:
total += sortedPrices[i]
toys.append(sortedPrices[i])
else:
break
print(f"He can buy items that cost {toys} for {total}")
print(f"The maximum is {len(toys)} items")
print(maximumToys(prices, k))输出:
He can buy items that cost [1, 5, 10, 12] for 28
The maximum is 4 items发布于 2021-02-17 15:35:51
问题出在这段代码上:
if total <= k:
total += sortedPrices[i]
toys.append(sortedPrices[i])您可以检查
在添加新元素之前添加新元素,而只有在以下情况下才应添加该元素:
不超过
添加新项目后。
因此,正确的代码应该是:
if total + sortedPrices[i] <= k: # add the item only when we don't exceed by adding it
total += sortedPrices[i]
toys.append(sortedPrices[i])发布于 2021-02-17 15:46:01
您的代码中的错误已由
克里希纳·乔拉西亚
..。
另一种方法是减去
来自
并检查是否
仍然大于或等于
然后递增
,否则会中断循环。您不需要在函数中打印完整的字符串消息。只需从你的方法中返回count的值即可。这是在各种编码实践网站上所期望的。
def maximumToys(prices, k):
prices.sort()
count = 0
for price in prices:
if k-price >= 0:
count = count + 1
k -= price
else:
break
return counthttps://stackoverflow.com/questions/66237444
复制相似问题