1402. Reducing Dishes
https://leetcode.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
-10^3 <= satisfaction[i] <= 10^3
Greedy Solution
贪心算法,满意度越大的菜越要放在后面做,延长等待时间;负数的菜在前面做有两方面效应,一方面可以增加等待时间从而增加总体的满意值,另一方面会在求和中引入负数。对于每一道菜都有做和不做两种选择,穷举完所有的情况后返回最大值。基本的贪心策略是排序,增加满意度高的菜的等待时间。正数的菜一定需要做,负数的菜两方面效应叠加后对总和的贡献是正的菜也值得做,也就是负数小到一定值,使得负效应大于正效应后就找到了结果的最大值。
首先对满意度递增排序,从后往前遍历,before
记录截止到当前菜的 satisfaction[i]
总和, sum
记录此前的结果总和加上做当前菜的结果,ans
记录全局最大值;当新一轮的 sum
小于之前记录的 ans
就可以返回结果。
排序的时间复杂度 O(nlogn),穷举求和的时间复杂度 O(n),总的时间复杂度 O(nlogn);空间复杂度 O(1)
class Solution {
public:
int maxSatisfaction(vector<int>& satisfaction) {
sort(satisfaction.begin(), satisfaction.end());
int n = satisfaction.size();
int ans = 0, before = 0, sum = 0;
for(int i = n-1; i >= 0; --i){
sum += before + satisfaction[i];
before += satisfaction[i];
if(sum < ans)
return ans;
ans = max(ans, sum);
}
return ans;
}
};
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reducing Dishes.
Memory Usage: 8.1 MB, less than 59.12% of C++ online submissions for Reducing Dishes.