Article Directory
1. Source title
Links: 5363. cook order
2. Description title
3. resolve title
Method One: Piggy + clever solution
The fourth question anomaly simple point very clear ideas ... ah.
Since cooking can be assigned in any order, it is easy to think of the array can be in ascending order, the highest number on the back, greedy processed.
After sorting, two- for
cycle problem, all the dishes are done, the lowest satisfaction dishes do, do all the rest of the dish, that is, from left to right, the left continues to discard a small value, resulting in a decreasing cooking range , you can put all the statistics out of greed, and then sort()
sort, to get the maximum results.
See the code below:
// 执行用时 :12 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :6.8 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
int maxSatisfaction(vector<int>& s) {
int flag = 1;
sort(s.begin(), s.end());
for (int i = 0; i < s.size(); ++i) {
int tmp = 0;
for (int j = i; j < s.size(); ++j) {
tmp += s[j] * flag;
flag++;
}
flag = 1;
s[i] = tmp;
}
int len = s.size();
sort(s.begin(), s.end());
return s.back() > 0 ? s.back() : 0;
}
};
Method two: greedy + + code optimization ingenious solution
Thinking the same method, but do not need to double for
up, its data structure is very characteristic of the sort can be judged from the back, each time adding a new number, the number will increase over the previous all together again, reaching topics Claim.
See the code below:
// 执行用时 :4 ms, 在所有 C++ 提交中击败了100.00%的用户
// 内存消耗 :6.7 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
int maxSatisfaction(vector<int>& satisfaction) {
sort(satisfaction.begin(), satisfaction.end());
int ans = 0, cnt = 0;
for (int i = satisfaction.size() - 1; i >= 0; --i) {
cnt += satisfaction[i];
if (cnt < 0) break;
ans += cnt;
}
return ans;
}
};