一个厨师收集了他 n 道菜的满意程度 satisfaction ,这个厨师做出每道菜的时间都是 1 单位时间。
一道菜的 「喜爱时间」系数定义为烹饪这道菜以及之前每道菜所花费的时间乘以这道菜的满意程度,也就是 time[i]*satisfaction[i] 。
请你返回做完所有菜 「喜爱时间」总和的最大值为多少。
你可以按 任意 顺序安排做菜的顺序,你也可以选择放弃做某些菜来获得更大的总和。
链接:https://leetcode-cn.com/problems/reducing-dishes
class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
func = lambda x,y: x*y
sorted_satisfaction = sorted(satisfaction, reverse=True)
if sorted_satisfaction[0] <= 0:
return 0
if sorted_satisfaction[-1] >= 0:
sorted_satisfaction = sorted(sorted_satisfaction)
temp_1 = list(range(1, len(sorted_satisfaction) + 1))
result = sum(list(map(func, sorted_satisfaction, temp_1)))
return result
for i in range(1, len(sorted_satisfaction)+1):
if i == len(sorted_satisfaction):
temp = sorted_satisfaction[:i]
if sum(sorted_satisfaction[:i]) <= 0:
temp = sorted_satisfaction[:i-1]
break
temp = sorted(temp)
temp_1 = list(range(1, len(temp)+1))
result = sum(list(map(func, temp, temp_1)))
return result
标准答案很简单:
class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort(reverse=True)
presum, ans = 0, 0
for si in satisfaction:
if presum + si > 0:
presum += si
ans += presum
else:
break
return ans
思路:
1.第一步排序排序排序,从大到小
2.思考终止条件:如果出现前n项和小于0的情况,那就不应该继续下去了。
自己写的太太太麻烦了!!!
收获:
1.巧用break
2.lamda:lambda函数可以接受任意数量的参数,但函数只能包含一个表达式。表达式是lambda函数执行的一段代码,它可以返回任何值,也可以不返回任何值。lambda函数可以返回函数对象。
func1=lambda 参数:一句话函数体(默认返回函数体内执行的内容)