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: Maximize Like-Time CoefficientInput: satisfaction = [-1, 0, 3, 1, 2]-10312Like-Time Coefficient Formulacoefficient = time[i] × satisfaction[i]Sum all coefficients for selected dishesOptimal Strategy: Sort and Select GreedilyAfter Sorting: [-1, 0, 1, 2, 3]-10123Cook all dishes:1×(-1) + 2×0 + 3×1 + 4×2 + 5×3Maximum Like-Time Coefficient: 25Greedy approach achieves optimal result in O(n log n) time
Understanding the Visualization
1
Input
Array of satisfaction values for n dishes
2
Process
Select dishes and order them to maximize sum of time×satisfaction
3
Output
Maximum possible like-time coefficient sum
Key Takeaway
🎯 Key Insight: Sort dishes and use greedy strategy - add dishes while their contribution (suffix sum) remains positive
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