[LeetCode] Reducing Dishes

1402. Reducing Dishes

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 dishes preparation.

Dishes can be prepared in any order and the chef can discard some dishes to get this maximum value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int maxSatisfaction(vector<int>& satisfaction) {
sort(satisfaction.begin(), satisfaction.end());
if(satisfaction.back() <= 0) return 0;
vector<int> sum{0};
int res = 0;
for(auto& n : satisfaction) {
sum.push_back(sum.back() + n);
res += n * (sum.size() - 1);
}
for(int i = 0; i < sum.size(); i++) {
if(sum.back() - sum[i] >= 0) break;
res -= (sum.back() - sum[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/07/10/PS/LeetCode/reducing-dishes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.