#1402

Reducing Dishes

Hard
ArrayDynamic ProgrammingGreedySortingGreedySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n² * 2^n)
O(n log n)
Space
O(n)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal solution leverages sorting and a greedy approach. By sorting the satisfaction levels, we can maximize the like-time coefficient by considering only the most satisfying dishes in the right order.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the satisfaction array in ascending order.
  2. 2Step 2: Initialize variables for the maximum sum and current sum.
  3. 3Step 3: Iterate from the end of the sorted array to the beginning, adding dishes to the current sum and updating the maximum sum if it increases.
solution.py10 lines
1def maxSatisfaction(satisfaction):
2    satisfaction.sort()
3    max_sum = 0
4    current_sum = 0
5    total = 0
6    for i in range(len(satisfaction) - 1, -1, -1):
7        total += satisfaction[i]
8        current_sum += total
9        max_sum = max(max_sum, current_sum)
10    return max_sum

Complexity note: The time complexity is dominated by the sorting step, which is O(n log n). The space complexity is O(1) since we are using a constant amount of extra space.

  • 1Sorting the satisfaction levels allows us to maximize the like-time coefficient effectively.
  • 2Only the most satisfying dishes contribute positively to the total; negative dishes should be discarded.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.