解法一 - 從分數最低的小朋友開始,如果鄰居有比較高分的小朋友就加糖果
class rate_pair
{
public:
int index;
int rate;
rate_pair(int id, int r) {
index = id;
rate = r;
}
};
class Compare
{
public:
bool operator() (rate_pair rate_pair_1, rate_pair rate_pair_2)
{
return rate_pair_1.rate > rate_pair_2.rate;
}
};
class Solution {
public:
int candy(vector<int>& ratings) {
// Corner case
int n = ratings.size();
if(n < 2) return n;
// Use a pq to hold ratings
priority_queue<rate_pair, std::vector<rate_pair>, Compare> pq;
for(int i=0; i<n; i++) {
rate_pair r(i, ratings[i]);
pq.push(r);
}
/*
while(!pq.empty()) {
cout << pq.top().index << " " << pq.top().rate << endl;
pq.pop();
}
*/
vector<int> candy(n, 1);
while(!pq.empty()) {
int curId = pq.top().index;
int curRate = pq.top().rate;
//cout << curId << " " << curRate << endl;
pq.pop();
// If neighbor is higher, add one to neighbor
int leftId = curId-1, rightId = curId+1;
if(leftId >= 0 && ratings[leftId] > curRate) candy[leftId] = max(candy[leftId], candy[curId]+1);
if(rightId < n && ratings[rightId] > curRate) candy[rightId] = max(candy[rightId], candy[curId]+1);
}
/*
cout << "candies: [";
for(auto c: candy) {
cout << c << ",";
}
cout << "]\n";
*/
return accumulate(candy.begin(), candy.end(), 0);
}
};
// idea: use pq to store (rating, index) pair, get min rating kid first, if neightbors have better rating, give the neighbor one more
Runtime: 64 ms, faster than 9.87% of C++ online submissions for Candy. Memory Usage: 13.3 MB, less than 5.99% of C++ online submissions for Candy.
我們在思考解法一的過程中,有發現到如果只從左邊往右掃,那就可能會無法處理向右遞減比左邊遞增長的例子,所以我們或許可以用兩個 array,一個紀錄從左往右的增加量,一個紀錄從右往左的增加量,最後再取 max 即可。
class Solution {
public:
int candy(vector<int>& ratings) {
// Corner case
int n = ratings.size();
if(n < 2) return n;
vector<int> candy(n, 1);
for(int i=1; i<n; i++) {
if(ratings[i] > ratings[i-1]) {
candy[i] = candy[i-1]+1;
}
}
for(int i=n-2; i>=0; i--) {
if(ratings[i] > ratings[i+1]) {
candy[i] = max(candy[i], candy[i+1]+1);
}
}
return accumulate(candy.begin(), candy.end(), 0);
}
};
Runtime: 28 ms, faster than 78.16% of C++ online submissions for Candy. Memory Usage: 10.7 MB, less than 56.51% of C++ online submissions for Candy.