Taro Logo

Reducing Dishes

#149 Most AskedHard
Topics:
ArraysGreedy Algorithms

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.

Example 1:

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).
Each dish is prepared in one unit of time.

Example 2:

Input: satisfaction = [4,3,2]
Output: 20
Explanation: Dishes can be prepared in any order, (2*1 + 3*2 + 4*3 = 20)

Example 3:

Input: satisfaction = [-1,-4,-5]
Output: 0
Explanation: People do not like the dishes. No dish is prepared.

Constraints:

  • n == satisfaction.length
  • 1 <= n <= 500
  • -1000 <= satisfaction[i] <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the satisfaction levels contain negative integers, and is it possible that all dishes have negative satisfaction?
  2. Are we required to use all the dishes provided in the input, or can we choose to cook only a subset of them?
  3. Does the order in which we choose and arrange the dishes matter for the final like-time coefficient calculation?
  4. What should be the return value if all available dishes have negative satisfaction and it's better not to cook any dish at all?
  5. Can the input array contain duplicate satisfaction values, and do they need to be treated as distinct dishes?

Brute Force Solution

Approach

Imagine you have a collection of different dishes you can make, each taking a certain amount of time to prepare and giving a certain amount of satisfaction. The brute force approach is to test every single combination of dishes you could possibly choose, and for each combination, try every possible way to arrange them in order to see which yields the highest total satisfaction.

Here's how the algorithm would work step-by-step:

  1. Start by listing every possible subset of dishes you could choose to make, from making just a single dish to making all of them.
  2. For each group of chosen dishes, consider every possible order in which you could cook and serve them.
  3. Calculate the satisfaction score for a specific order by multiplying each dish's satisfaction value by its position in the cooking sequence, starting with one for the first dish, two for the second, and so on, and then add those numbers together.
  4. Compute this total satisfaction score for every single ordered combination you have generated.
  5. Compare all the calculated scores against each other to find the maximum possible satisfaction you can achieve.
  6. Return the highest score found among all the tested possibilities as your final answer.

Code Implementation

import itertools


def max_satisfaction(satisfaction):
    # Generate all possible subsets and their valid permutations to evaluate every cooking order
    maximum_satisfaction_found = 0

    for subset_size in range(1, len(satisfaction) + 1):
        for dish_combination in itertools.combinations(satisfaction, subset_size):
            for cooking_sequence in itertools.permutations(dish_combination):
                current_satisfaction = 0
                for time_index, dish_value in enumerate(cooking_sequence):
                    current_satisfaction += dish_value * (time_index + 1)

                # Keep track of the highest satisfaction score discovered across all tested orders
                if current_satisfaction > maximum_satisfaction_found:
                    maximum_satisfaction_found = current_satisfaction

    # Return the maximum satisfaction achieved, or zero if no dishes yield positive results
    return maximum_satisfaction_found

Big(O) Analysis

Time Complexity
O(n * 2^n) – The brute force approach requires generating every possible subset of the n dishes, resulting in 2^n combinations, and then for each chosen subset of size k, trying all k! possible ordering permutations to calculate the satisfaction score. Because generating subsets and their permutations explodes factorially alongside the exponential number of subsets, the total operations scale roughly as n * 2^n * n!, which is heavily dominated by the factorial permutations. Simplifying this worst-case combinatorial exploration yields a time complexity bounded by O(n * 2^n).
Space Complexity
O(1) – The space complexity is O(1) because the brute force generation of all subsets, arrangements, and subsequent satisfaction score computations rely entirely on a few constant variables to track the current and maximum satisfaction totals. No additional dynamic data structures, such as recursion stacks or temporary memory arrays, scale with the number of dishes N. Therefore, the extra memory used remains constant regardless of the input size.

Optimal Solution

Approach

To get the absolute best total score for your dishes, the secret is to prepare the most delicious ones last so they get multiplied by the highest possible time factor. By sorting the dishes by their tastiness and working backward from the end of your cooking schedule, you can easily figure out the exact moment when adding another dish stops helping and starts hurting your total score.

Here's how the algorithm would work step-by-step:

  1. Sort all of your available dishes from the least tasty to the most tasty.
  2. Imagine you have a strict cooking schedule where you can choose to make some or all of these dishes, keeping them in the sorted order.
  3. Start by thinking about making only the absolute tastiest dish at the very last moment to get its maximum possible score multiplier.
  4. Work backward by considering the next tastiest dish and placing it just before the previous one in your schedule.
  5. Keep a running total of your satisfaction score as you add each dish to earlier and earlier time slots.
  6. Pay close attention to whether adding another dish makes your total score go up or down.
  7. The moment adding a less tasty dish causes your total score to stop increasing and start dropping, stop right there.
  8. Your optimal strategy is complete, having found the exact combination of dishes that gives you the highest possible final score.

Code Implementation

class Solution:
    def maxSatisfaction(self, satisfaction_levels: list[int]) -> int:
        # Sorting ensures least tasty dishes are considered first for earlier time slots.
        satisfaction_levels.sort()
        
        max_total_score = 0
        current_running_sum = 0
        cumulative_score = 0
        
        # Working backward allows tastiest dishes to receive the highest multipliers.
        for dish_satisfaction in reversed(satisfaction_levels):
            current_running_sum += dish_satisfaction
            
            # If adding the dish decreases or halts growth, further additions will hurt.
            if current_running_sum > 0:
                cumulative_score += current_running_sum
                max_total_score = max(max_total_score, cumulative_score)
            else:
                break
                
        return max_total_score

Big(O) Analysis

Time Complexity
O(n log n) – The time complexity is driven by two main phases operating on the input size n representing the number of dishes. First, sorting all the dishes from least to most tasty takes O(n log n) time. Second, iterating backward through the sorted dishes to calculate the running satisfaction score takes a single linear pass of O(n) time. Since the logarithmic sorting phase dominates the linear accumulation phase, the total operations simplify to O(n log n).
Space Complexity
O(1) – The algorithm requires a constant amount of extra memory beyond the input itself, specifically for a few scalar tracking variables like the running satisfaction score and loop counters. Since we sort the dishes in place and work backward through them without allocating any auxiliary data structures like temporary lists or hash maps, the extra memory usage remains entirely fixed. Therefore, as the number of dishes N grows, the auxiliary space complexity stays constant at O(1).

Edge Cases

Empty array or null input representing no dishes
How to Handle:
Return zero immediately since no dishes can be prepared to generate satisfaction.
Array containing only negative satisfaction values
How to Handle:
Sort the array and check if the total sum of all negative values fails to improve the coefficient, returning zero by picking no dishes.
Array containing a single dish with a positive or negative satisfaction value
How to Handle:
Return the maximum of zero and the single dish satisfaction because taking it at time one yields its direct value.
All elements in the satisfaction array are identical
How to Handle:
Sorting leaves identical elements adjacent, and our greedy accumulation correctly evaluates whether including all or a subset maximizes the total sum.
Highly skewed distribution with extremely large positive and negative numbers
How to Handle:
Sorting the array places the smallest negatives first and largest positives last, ensuring greedy prefix sums maximize the like-time coefficient effectively.
Maximum-sized inputs with up to five hundred elements
How to Handle:
An O(N log N) sorting approach or O(N) suffix-sum greedy approach scales efficiently well within standard time limits.
Duplicate satisfaction values present multiple times
How to Handle:
Sorting preserves relative order of duplicates and the greedy accumulation treats them independently as distinct sequential dishes.
Inputs with extreme boundary values near integer limits
How to Handle:
Standard 32-bit signed integers are sufficient since the maximum possible sum fits well within standard integer ranges without overflow.
0/245 completed