Reducing Dishes — LeetCode 1402 Python Solution

HardGreedyArrayDynamic ProgrammingSorting
Problem
#1402
Pattern
Greedy
Reading time
2 min

The problem

A chef has collected data on the satisfaction level of his n dishes. Chef can cook any dish in 1 unit of time.

Example

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).

Python solution

Python
class Solution:
    def maxSatisfaction(self, satisfaction: List[int]) -> int:
        satisfaction.sort(reverse=True)
        ans = s = 0
        for x in satisfaction:
            s += x
            if s <= 0:
                break
            ans += s
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1402. Reducing Dishes is filed here because LeetCode tags it Greedy, which is the vocabulary this hub collects.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1402. Reducing Dishes?
LeetCode 1402. Reducing Dishes is rated Hard on LeetCode.
What is the time complexity of LeetCode 1402. Reducing Dishes?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1402. Reducing Dishes?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1402. Reducing Dishes cover?
LeetCode 1402. Reducing Dishes is tagged Greedy, Array, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview