Reducing Dishes - Problem

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.

Input & Output

Example 1 — Mixed Values
$ Input: satisfaction = [-1,0,3,1,2]
Output: 25
💡 Note: After sorting: [-1,0,1,2,3]. Optimal selection is dishes with satisfaction [1,2,3] cooked in this order. Like-time coefficient: 1×1 + 2×2 + 3×3 = 14. But we can include all dishes: 1×(-1) + 2×0 + 3×1 + 4×2 + 5×3 = 20. Actually, using greedy: 25.
Example 2 — All Negative
$ Input: satisfaction = [-2,-3,-1]
Output: 0
💡 Note: All satisfaction values are negative. Best strategy is to cook no dishes, resulting in sum = 0.
Example 3 — All Positive
$ Input: satisfaction = [4,3,2]
Output: 20
💡 Note: All positive values. Sort to [2,3,4]. Cook in this order: 1×2 + 2×3 + 3×4 = 2 + 6 + 12 = 20.

Constraints

  • 1 ≤ satisfaction.length ≤ 500
  • -1000 ≤ satisfaction[i] ≤ 1000

Visualization

Tap to expand
Reducing Dishes - Greedy Optimization INPUT satisfaction array -1 0 3 1 2 i=0 i=1 i=2 i=3 i=4 Satisfaction Levels [-1, 0, 3, 1, 2] ALGORITHM STEPS 1 Sort Descending [3, 2, 1, 0, -1] 2 Compute Prefix Sum Add dishes greedily 3 Check Running Sum Stop if sum becomes neg 4 Accumulate Total Sum all prefix sums Iteration Table Dish Sum Total +3 3 3 +2 5 8 +1 6 14 +0 6 20 -1 5 25 FINAL RESULT Optimal Order (time multiplier) -1 t=1 0 t=2 1 t=3 2 t=4 3 t=5 Like-time Calculation: 1 x (-1) = -1 2 x 0 = 0 3 x 1 = 3 4 x 2 = 8 5 x 3 = 15 Total = 25 Maximum Sum 25 OK - Optimal solution found Key Insight: Sort dishes by satisfaction in descending order. Greedily add each dish and track the running sum. Each dish added contributes its satisfaction to ALL future time slots. The total equals the sum of all prefix sums. Include a dish only if the running sum stays positive (adding value to the total). TutorialsPoint - Reducing Dishes | Greedy Optimization Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen