题解 | #分糖果问题#
分糖果问题
https://www.nowcoder.com/practice/76039109dd0b47e994c08d8319faa352
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * pick candy * @param arr int整型vector the array * @return int整型 */ int candy(vector<int>& arr) { // write code here std::vector<int> candy_num(arr.size(), 1); for (int i = 1; i < arr.size(); i++) { if (arr[i] > arr[i - 1] && candy_num[i] <= candy_num[i - 1]) { candy_num[i] = candy_num[i - 1] + 1; } } for (int i = arr.size() - 2; i >= 0; i--) { if (arr[i] > arr[i + 1] && candy_num[i] <= candy_num[i + 1]) { candy_num[i] = candy_num[i + 1] + 1; } } int res = 0; for (int i : candy_num) { res += i; } return res; } };