#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param k int整型
# @param w int整型
# @param profits int整型一维数组
# @param costs int整型一维数组
# @return int整型
#
import heapq
class Solution:
def findMaximizedProfits(self , k: int, w: int, profits: List[int], costs: List[int]) -> int:
# Pair each cost with its corresponding profit and sort by cost
cows = sorted(zip(costs, profits), key=lambda x: x[0])
n = len(cows)
heap = []
total = 0
i = 0
for _ in range(k):
# Add all possible cows that can be afforded with current w
while i < n and cows[i][0] <= w:
cost, profit = cows[i]
heapq.heappush(heap, -profit) # Use negative to simulate max heap
i += 1
if not heap:
return total # No more cows can be bought
# Select the cow with maximum profit
max_profit = -heapq.heappop(heap)
total += max_profit
w += max_profit
return total
使用QwQ 32B Q6_K生成,模型参数使用官方文档的参数。
prompt:以下是一道算法题,请你用尽可能低的时间和空间复杂度,尽可能短的代码,在符合题目要求的情况下完成这道题,并给出解题思路,\n代表换行:“(题干)”

京公网安备 11010502036488号