Reducing Dishes — LeetCode 1402 Python Solution
HardGreedyArrayDynamic ProgrammingSorting
- Problem
- #1402
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\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.