这题就是从左到右对递增的点进行刷点,再从右到左对递增的点进行刷点。时间复杂度和空间复杂度都为O(n)。注意如果两个相邻的点ratings一样,则不必保持candy数一样(个人认为很不合理).
1 class Solution { 2 public: 3 int candy(vector<int> &ratings) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 vector<int> res(ratings.size(), 1); 7 for (int i = 1; i < ratings.size(); i++) 8 if (ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1; 9 for (int i = ratings.size()-2; i >= 0; i--) 10 if (ratings[i] > ratings[i+1]) res[i] = max(res[i], res[i+1] + 1); 11 int ans = 0; 12 for (int i = 0; i < res.size(); i++) ans += res[i]; 13 return ans; 14 } 15 };
C#
1 public class Solution { 2 public int Candy(int[] ratings) { 3 int[] res = new int[ratings.Length]; 4 for (int i = 0; i < ratings.Length; i++) res[i] = 1; 5 for (int i = 1; i < ratings.Length; i++) { 6 if (ratings[i] > ratings[i-1]) res[i] = res[i-1] + 1; 7 } 8 for (int i = ratings.Length-2; i >= 0; i--) { 9 if (ratings[i] > ratings[i+1]) res[i] = Math.Max(res[i], res[i+1] + 1); 10 } 11 int ans = 0; 12 for (int i = 0; i < res.Length; i++) ans += res[i]; 13 return ans; 14 } 15 }