Reducing Dishes (LeetCode 1402): Solution and Explanation

Hard
Array
Greedy
Sorting
Dynamic programming

Each dish has a satisfaction value, and a dish cooked at time t is worth t times that value. You may drop dishes and cook the rest in any order. Return the largest total you can reach.

Intuition

Whatever set of dishes you cook, you want the best ones to finish last, where the multiplier is biggest. So the chosen dishes are always cooked in increasing order, and the only real question is which dishes to keep.

Sort the dishes from best to worst. If you decide to keep some dish, keeping every better dish too can only help, so the chosen set is a prefix of this sorted order.

Now grow the prefix one dish at a time and put each new dish at the front of the cooking order. Every dish that was already chosen moves one slot later and gets counted once more, and the new dish is counted once at time 1. The total therefore grows by exactly the sum of all chosen dishes, which we call suffix.

As long as suffix is positive, adding the dish pays off. The values only get smaller from here, so once suffix stops being positive it never becomes positive again, and you can stop.

Approach: Sort descending plus running suffix sum

  1. Sort satisfaction from largest to smallest.
  2. Set total = 0 and suffix = 0.
  3. For each value s, add it to suffix.
  4. If suffix <= 0, stop. Otherwise add suffix to total.
  5. Return total.

Step-by-step example

satisfaction = [-1,-8,0,5,-9]
  1. Sorted best to worst: [5, 0, -1, -8, -9].
  2. Dish 5: suffix = 5, total = 5. The menu is [5] at time 1.
  3. Dish 0: suffix = 5, total = 10. The menu is [0, 5], so 5 now cooks at time 2.
  4. Dish -1: suffix = 4, total = 14. The menu is [-1, 0, 5], worth -1 + 0 + 15 = 14.
  5. Dish -8: suffix = -4, which is not positive, so stop. The answer is 14.

Code: Python, Java, C++

1class Solution:
2    def maxSatisfaction(self, satisfaction: List[int]) -> int:
3        satisfaction.sort(reverse=True)
4        total = 0
5        suffix = 0
6        for s in satisfaction:
7            suffix += s
8            if suffix <= 0:
9                break
10            total += suffix
11        return total
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting dominates. The scan after it is a single pass that may stop early.

Space

O(1)

Only two running sums are kept, apart from whatever the sort uses internally.

Other approaches

Try every prefix (time O(n^2), space O(1))

After sorting, compute the like-time sum of each prefix from scratch and keep the best. It is easy to verify but repeats work for every prefix.

Dynamic programming over dishes and time (time O(n^2), space O(n^2) or O(n) with rolling rows)

Sort ascending and let dp[i][t] be the best sum using dishes from i onward when the next dish cooks at time t. Each dish is either cooked at time t or skipped. It is the general pattern for take-or-skip problems but is far slower than the greedy.

Common mistakes

  • Stopping at the first negative dish. A negative dish can still help if the dishes already chosen are large enough, as in Example 1 where -1 is kept.
  • Sorting ascending and scanning forward. The prefix trick needs the best dishes first so each new dish goes to the front.
  • Using suffix < 0 as the stop test. When suffix is 0 the gain is 0, so stopping or continuing gives the same total, but continuing can only lose afterwards.
  • Forgetting that cooking nothing is allowed, so the answer is never negative.

Frequently asked questions

Why does adding a dish at the front increase the total by the running sum?

Putting a dish at time 1 pushes every chosen dish one slot later, so each one adds its own value once more. The new dish adds its value once. Together that is the sum of all chosen dishes.

Why is the chosen set always a prefix of the sorted order?

If you keep a dish but drop a better one, swapping the dropped dish in for the kept one at the same time slot never lowers the total. Repeating the swap gives a prefix of the best dishes.

Can the running sum become positive again after it drops to zero or below?

No. The remaining dishes are no larger than the one that made it non-positive, and once that dish is negative or zero every later one is too, so the sum can only stay the same or shrink.

Is this really a dynamic programming problem?

It is often tagged that way, and a take-or-skip DP works. The greedy exchange argument shows the DP always picks a prefix of the sorted dishes, which is why the O(n log n) scan is enough.