You are given an array of integers sat
where sat[i]
represents the satisfaction level of the i
-th dish. A chef can prepare any subset of these dishes in any order. For each dish prepared at time t
(where t
starts at 1 and increases by 1 for each subsequent dish), the chef gains t * sat[i]
points of satisfaction.
The chef wants to maximize the total sum of satisfaction points by choosing an optimal subset and order of dishes. The chef may choose to discard some dishes (i.e., not prepare them at all).
Constraints:
At first glance, it might seem necessary to try every possible subset and permutation of the dishes, since both selection and ordering affect the result. However, this brute-force method quickly becomes infeasible due to the exponential number of possibilities.
To optimize, let's look for patterns:
Let's break down the steps to solve this problem efficiently:
This greedy approach works because adding a negative satisfaction dish only helps if the increase in time factors for the remaining dishes outweighs the penalty from the negative value.
Sample Input: sat = [-1, -8, 0, 5, -9]
[-9, -8, -1, 0, 5]
The key insight is to sort the dishes by satisfaction and build the optimal subset backwards, always checking if including another dish increases the total satisfaction. This greedy method efficiently finds the best answer, avoiding the need to check all possible combinations and orders. By focusing on how time factors increase for each earlier dish, we elegantly maximize the final satisfaction score.
class Solution:
def maxSatisfaction(self, satisfaction):
satisfaction.sort()
total, res, curr = 0, 0, 0
for sat in reversed(satisfaction):
curr += sat
if curr > 0:
res += curr
else:
break
return res
class Solution {
public:
int maxSatisfaction(vector<int>& satisfaction) {
sort(satisfaction.begin(), satisfaction.end());
int res = 0, curr = 0;
for (int i = satisfaction.size() - 1; i >= 0; --i) {
curr += satisfaction[i];
if (curr > 0) {
res += curr;
} else {
break;
}
}
return res;
}
};
class Solution {
public int maxSatisfaction(int[] satisfaction) {
Arrays.sort(satisfaction);
int res = 0, curr = 0;
for (int i = satisfaction.length - 1; i >= 0; --i) {
curr += satisfaction[i];
if (curr > 0) {
res += curr;
} else {
break;
}
}
return res;
}
}
var maxSatisfaction = function(satisfaction) {
satisfaction.sort((a, b) => a - b);
let res = 0, curr = 0;
for (let i = satisfaction.length - 1; i >= 0; --i) {
curr += satisfaction[i];
if (curr > 0) {
res += curr;
} else {
break;
}
}
return res;
};