Reducing Dishes Problem
Description
LeetCode Problem 1402.
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 preparing some amount of dishes.
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 do not like the dishes. No dish is prepared.
Constraints:
n == satisfaction.length1 <= n <= 500-1000 <= satisfaction[i] <= 1000
Solution
Approach: Greedy on the Sorted Dishes
Two observations make this easy.
The best order is increasing. Once we have chosen a set of dishes, the like-time sum 1 * a1 + 2 * a2 + ... is largest when the dish with the largest satisfaction gets the largest time. So the chosen dishes are cooked from the smallest to the largest satisfaction.
Adding dishes from the top down. Sort the dishes in decreasing order and consider taking the best k of them. If we put one more dish x (the next best) at the front of the menu, every dish already chosen is cooked one unit later, which adds their sum once more, and x itself gets time 1. So the total grows by x + (sum of the dishes already chosen), that is, by the sum of the chosen dishes including x.
So keep a running sum suffix of the chosen dishes. For each dish in decreasing order, add it to suffix. If suffix is still positive, the dish makes the total larger, so add suffix to the answer. Once suffix <= 0, stop: every later dish is no better and would only make the running sum smaller.
In Example 1, the sorted dishes are 5, 0, -1, -8, -9. The running sums are 5, 5, 4, -4, so we take three dishes for 5 + 5 + 4 = 14. If even the best dish is non-positive (Example 3), we cook nothing and the answer is 0.
Complexity: O(n log n) time for sorting and O(1) extra space (apart from the sort).
class Solution:
def maxSatisfaction(self, satisfaction: List[int]) -> int:
satisfaction.sort(reverse=True)
ans = suffix = 0 # suffix = sum of the dishes chosen so far (the best ones)
for x in satisfaction:
suffix += x
if suffix <= 0: # adding this dish (and any worse one) no longer helps
break
ans += suffix # cooking x first shifts every chosen dish one step later
return ans