We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reducing Dishes

Number: 1503

Difficulty: Hard

Paid? No

Companies: Bloomberg, Microsoft


Problem Description

A chef has collected data on the satisfaction level of his n dishes. The like-time coefficient of a dish is defined as (time[i] * satisfaction[i]), where time[i] represents the unit time the dish is cooked including any previously cooked dishes. The chef can cook the dishes in any order and is allowed to discard some dishes. The goal is to find the maximum total like-time coefficient possible.


Key Insights

  • Sort the satisfaction level array to order the dishes by preference.
  • Cooking dishes with higher satisfaction later in the sequence leverages the increasing time multiplier.
  • A greedy backward iteration can efficiently decide which dishes to include.
  • Adding a dish is beneficial only if its inclusion increases the cumulative sum (i.e., net benefit across all positions).

Space and Time Complexity

Time Complexity: O(n log n) due to sorting. Space Complexity: O(1) extra space (in-place sorting aside from input storage).


Solution

The solution involves first sorting the satisfaction levels in ascending order. Then, iterate over the sorted array from right to left, accumulating a running sum. At each step, if including the current dish (by adding its satisfaction value to the running sum) results in a positive cumulative sum, it is beneficial to cook that dish, so update the total like-time coefficient accordingly. This greedy approach ensures that only beneficial dishes are considered, while the multiplier effect of cooking a dish later is automatically captured by the accumulated sum.


Code Solutions

# Python solution with detailed comments

def maxSatisfaction(satisfaction):
    # Sort the satisfaction levels in ascending order
    satisfaction.sort()
    
    total_like_time = 0  # Total maximum like-time coefficient
    cumulative_sum = 0   # Cumulative sum of included satisfaction values
    
    # Iterate backwards from the highest satisfaction values
    for i in range(len(satisfaction) - 1, -1, -1):
        # Check if including the current dish improves the overall sum
        if cumulative_sum + satisfaction[i] > 0:
            cumulative_sum += satisfaction[i]
            total_like_time += cumulative_sum
        else:
            # Stop if including the dish does not yield benefit
            break
            
    return total_like_time

# Example usage:
if __name__ == '__main__':
    print(maxSatisfaction([-1, -8, 0, 5, -9]))  # Expected Output: 14
← Back to All Questions