MCPcopy Create free account
hub / github.com/Ainevsia/Leetcode-Rust / candy

Method candy

135. Candy/Solution.cpp:15–35  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13class Solution {
14public:
15 int candy(vector<int>& ratings) {
16 if (ratings.size() <= 1) return ratings.size();
17 int total = 1, prev = 1, countDown = 0;
18 for (int i = 1; i < ratings.size(); i++) {
19 if (ratings[i] >= ratings[i-1]) {
20 if (countDown > 0) {
21 total += countDown*(countDown+1)/2; // arithmetic progression
22 if (countDown >= prev) total += countDown - prev + 1;
23 countDown = 0;
24 prev = 1;
25 }
26 prev = ratings[i] == ratings[i-1] ? 1 : prev+1;
27 total += prev;
28 } else countDown++;
29 }
30 if (countDown > 0) { // if we were descending at the end
31 total += countDown*(countDown+1)/2;
32 if (countDown >= prev) total += countDown - prev + 1;
33 }
34 return total;
35 }
36};
37
38int main() {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected