加载中...
1402-做菜顺序(Reducing Dishes)
发表于:2021-12-03 | 分类: 困难
字数统计: 766 | 阅读时长: 3分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/reducing-dishes

英文原文

A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.

Like-time coefficient of a dish is defined as the time taken to cook that dish including previous dishes multiplied by its satisfaction level i.e. time[i] * satisfaction[i].

Return the maximum sum of like-time coefficient that the chef can obtain after dishes preparation.

Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.

 

Example 1:

Input: satisfaction = [-1,-8,0,5,-9]
Output: 14
Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14).
Each dish is prepared in one unit of time.

Example 2:

Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)

Example 3:

Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People don't like the dishes. No dish is prepared.

Example 4:

Input: satisfaction = [-2,5,-1,0,3,-3]
Output: 35

 

Constraints:

  • n == satisfaction.length
  • 1 <= n <= 500
  • -1000 <= satisfaction[i] <= 1000

中文题目

一个厨师收集了他 n 道菜的满意程度 satisfaction ,这个厨师做出每道菜的时间都是 1 单位时间。

一道菜的 「喜爱时间」系数定义为烹饪这道菜以及之前每道菜所花费的时间乘以这道菜的满意程度,也就是 time[i]*satisfaction[i] 。

请你返回做完所有菜 「喜爱时间」总和的最大值为多少。

你可以按 任意 顺序安排做菜的顺序,你也可以选择放弃做某些菜来获得更大的总和。

 

示例 1:

输入:satisfaction = [-1,-8,0,5,-9]
输出:14
解释:去掉第二道和最后一道菜,最大的喜爱时间系数和为 (-1*1 + 0*2 + 5*3 = 14) 。每道菜都需要花费 1 单位时间完成。

示例 2:

输入:satisfaction = [4,3,2]
输出:20
解释:按照原来顺序相反的时间做菜 (2*1 + 3*2 + 4*3 = 20)

示例 3:

输入:satisfaction = [-1,-4,-5]
输出:0
解释:大家都不喜欢这些菜,所以不做任何菜可以获得最大的喜爱时间系数。

示例 4:

输入:satisfaction = [-2,5,-1,0,3,-3]
输出:35

 

提示:

  • n == satisfaction.length
  • 1 <= n <= 500
  • -10^3 <= satisfaction[i] <= 10^3

通过代码

高赞题解

思路

  1. 贪心
  2. 越往后乘积越大,越大的数应该放在最后,所以先排个序
  3. 从后面一个一个加入,每新加一个数,之前加过的所有数都会多加一遍

答题

[]
int maxSatisfaction(vector<int>& satisfaction) { sort(satisfaction.rbegin(), satisfaction.rend()); int ans = 0; int sum = 0; for (int i = 0; i < satisfaction.size(); i++) { sum += satisfaction[i]; if (sum < 0) break; ans += sum; } return ans; }

致谢

感谢您的观看,希望对您有帮助,欢迎热烈的交流!

如果感觉还不错就点个赞吧~

这是 我的leetcode ,帮助我收集整理题目,可以方便的 visual studio 调试,欢迎关注,star

统计信息

通过次数 提交次数 AC比率
9986 13258 75.3%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1400-构造 K 个回文字符串(Construct K Palindrome Strings)
下一篇:
1391-检查网格中是否存在有效路径(Check if There is a Valid Path in a Grid)
本文目录
本文目录