C++實現——小孩分糖果問題
阿新 • • 發佈:2019-02-13
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//分糖果的問題
/*
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
*/
/*
解題思路:
遍歷兩邊,首先每個人得一塊糖,第一遍從左到右,若當前點比前一個點高就比前者多一塊。
這樣保證了在一個方向上滿足了要求。第二遍從右往左,若左右兩點,左側高於右側,但
左側的糖果數不多於右側,則左側糖果數等於右側糖果數+1,這就保證了另一個方向上滿足要求。
最後將各個位置的糖果數累加起來就可以了。
*/
int candyCount(vector<int>&rating) {
int res = 0;
//孩子總數
int n = rating.size();
//糖果集合
vector<int> candy(n, 1 );
//從左往右遍歷
for (int i = 0;i < n - 1;i++) {
if (rating[i + 1] > rating[i])candy[i + 1] = candy[i] + 1;
}
//從右往左
for (int i = n - 1;i > 0;i--) {
if (rating[i - 1] > rating[i] && candy[i - 1] <= candy[i])candy[i - 1] = candy[i] + 1;
}
//累加結果
for (auto a : candy) {
res += a;
}
return res;
}
//測試函式
int main() {
vector<int> rating{1,3,2,1,4,5,2};
cout << candyCount(rating) << endl;
return 0;
}