The relationship between ratings [I + 1] and ratings [I] is as follows:
1. Equal. When the value is equal, ratings [I + 1] has 1 candy.
2. Ratings [I + 1]> ratings [I]. In this case, you need to find the incremental Sequence starting with ratings [I.
3. Ratings [I + 1] <ratings [I]. In this case, you need to find the descending sequence starting with ratings [I.
For a random ascending sequence [2 3 4 5 6], the corresponding number of Sweets is [1 2 3 4 x].
For a random descending sequence [6 5 4 3 2], the corresponding number of Sweets is [x 4 3 2 1].
X indicates the number of sweets corresponding to the elements in the ascending and descending serial communication. It should be a large value in the length of the ascending sequence and the length of the descending sequence
The Code is as follows:
int candy(vector<int> &ratings) { if (ratings.size() == 0) return 0; int sum = 0; int candyNum = 1; for (int i = 0; i < ratings.size() - 1;) { if (ratings[i] == ratings[i + 1]) { //if is the same rating, reset candy num. ie: 1 3 3, for the 2nd 3, candy num is 1 sum += candyNum;//add current candy num i++; candyNum = 1;//set next candy num to 1 } else if (ratings[i] < ratings[i + 1]) { // find ascending sequence, until i is the end of sequence. ie: 1 2 3 1, ratings[i] is 3 for (;i < ratings.size() - 1 && ratings[i] < ratings[i + 1]; i++) sum += (candyNum++); } else if (ratings[i] > ratings[i + 1]) { // find descending sequence, until i is the end of sequence. ie: 3 2 1 3, rating[i] is 1 int decCount = 1; for (; i < ratings.size() - 1 && ratings[i] > ratings[i + 1]; i++) sum += (decCount++); sum += max(candyNum, decCount);//add first element of the sequence //remove last element of the sequence, as i is the end of sequence, and i's candy num shouldn't be calculated into sum sum --; candyNum = 1; } } sum += candyNum; return sum; }
Candy [leetcode] O (n) time complexity, O (1) space complexity method