MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / candies

Function candies

cpp/Greedy/candies.cpp:5–28  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

3#include <algorithm>
4
5int candies(std::vector<int>& ratings) {
6 int n = ratings.size();
7 // Ensure each child starts with 1 candy.
8 std::vector<int> candies(n, 1);
9 // First pass: for each child, ensure the child has more candies
10 // than their left-side neighbor if the current child's rating is
11 // higher.
12 for (int i = 1; i < n; i++) {
13 if (ratings[i] > ratings[i - 1]) {
14 candies[i] = candies[i - 1] + 1;
15 }
16 }
17 // Second pass: for each child, ensure the child has more candies
18 // than their right-side neighbor if the current child's rating is
19 // higher.
20 for (int i = n - 2; i >= 0; i--) {
21 if (ratings[i] > ratings[i + 1]) {
22 // If the current child already has more candies than their
23 // right-side neighbor, keep the higher amount.
24 candies[i] = std::max(candies[i], candies[i + 1] + 1);
25 }
26 }
27 return std::accumulate(candies.begin(), candies.end(), 0);
28}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected