计算机科学基础leetcode刷题贪心 贪心 2024-03-16 Source Edit History 135. 分发糖果 Problem: 135. 分发糖果 Referencehttps://leetcode.cn/problems/candy/solutions/17847/candy-cong-zuo-zhi-you-cong-you-zhi-zuo-qu-zui-da-/?envType=study-plan-v2&envId=top-interview-150 复杂度时间复杂度: 添加时间复杂度, 示例: $O(n)$ 空间复杂度: 添加空间复杂度, 示例: $O(n)$ Code[]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465class Solution {public: int candy(vector<int>& ratings) { vector<int> left(ratings.size(), 1); vector<int> right(ratings.size(), 1); int count = 0; for (int i = 1; i < ratings.size(); i++) { // 左规则 if (ratings[i] > ratings[i - 1]) { left[i] = left[i - 1] + 1; } } for (int i = ratings.size() - 2; i >= 0; i--) { // 右规则 if (ratings[i] > ratings[i + 1]) { right[i] = right[i + 1] + 1; } count += std::max(left[i], right[i]); // std::cout << i; // std::cout << count; // std::cout << endl; } count += std::max(left[ratings.size()-1],right[ratings.size()-1]); // for (int i = 0; i < ratings.size(); i++) { // std::cout << left[i]; // } // std::cout << endl; // for (int i = 0; i < ratings.size(); i++) { // std::cout << right[i]; // } // std::cout << endl; return count; }};