C++ 0135.cpp
class Solution {
public:
int candy(vector<int>& ratings) {
vector<int> candies(ratings.size(), 1);
// left kid
for (int i = 1; i < ratings.size(); i++)
if (ratings[i] > ratings[i-1])
candies[i] = candies[i-1]+1;
// right kid
for (int i = ratings.size() - 2; i >= 0; i--)
if (ratings[i] > ratings[i+1])
candies[i] = max(candies[i], candies[i+1]+1);
int result = 0;
for (auto c : candies)
result += c;
return result;
}
};
Difficulty
and has an acceptance rate of about 49% (2+ million submissions).
Typical patterns to solve this problem:
- Array
- Greedy
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic distribution problem where each element in a sequence must receive a positive integer value respecting relative ordering constraints. The algorithm proceeds in three distinct phases: an initial allocation, a forward sweep that enforces increasing relationships, and a backward sweep that resolves decreasing relationships. A final aggregation yields the total count.
Initialization
At the outset a vector named candies is created with the same length as the input ratings. Every entry is seeded with the value 1, guaranteeing the minimum requirement that each position receives at least one unit.
vector<int> candies(ratings.size(), 1);
Left-to-Right Pass
The first traversal moves from the second element to the end. Whenever the current rating exceeds the previous rating, the algorithm raises the current candy count to one more than the predecessor’s count. This step propagates the minimal increasing sequence from left to right.
for (int i = 1; i < ratings.size(); i++)
if (ratings[i] > ratings[i-1])
candies[i] = candies[i-1] + 1;
Right-to-Left Pass
The second traversal walks backward from the penultimate element to the start. If a rating is greater than its right neighbor, the algorithm ensures the current candy count is at least one more than the neighbor’s count, using max to preserve any larger value already assigned during the forward pass. This resolves decreasing patterns while preserving previously established increases.
for (int i = ratings.size() - 2; i >= 0; i--)
if (ratings[i] > ratings[i+1])
candies[i] = max(candies[i], candies[i+1] + 1);
Accumulation
After both sweeps, the vector holds the minimal valid distribution. A simple loop sums all entries to produce the final result.
int result = 0;
for (auto c : candies)
result += c;
return result;
Edge Cases Handled
When the input contains a single element, the initialization creates a vector of length 1 with a value of 1, and both sweeps are effectively no-ops, resulting in a correct total of 1. If the ratings are strictly monotonic-either entirely increasing or entirely decreasing-the forward or backward pass respectively assigns a strictly ascending sequence of counts, while the other pass leaves the values unchanged, satisfying the ordering constraints. When adjacent ratings are equal, neither conditional in the sweeps triggers, leaving the default value of 1 for those positions, which complies with the rule that equal ratings impose no ordering requirement.
Performance Optimizations
The algorithm uses two linear passes over the data, each updating the candies vector in place without auxiliary structures, which minimizes memory overhead. The use of max in the backward pass avoids a separate comparison step, directly reconciling the two directional constraints. By initializing all entries to 1, the code eliminates the need for a separate check for the minimum requirement during the sweeps. The final aggregation employs a range-based loop, which the compiler can efficiently translate into a tight iteration. Overall, the solution achieves the desired outcome with a compact memory footprint and a constant number of passes proportional to the input size.
ELI5 - Simplified Explanation
Imagine a row of children standing in a line, and each child has a certain number of stars representing how well they did on a drawing. You want to give them candies, but you have two special rules to make sure everyone feels happy. First, every child must get at least one candy. Second, if a child has more stars than the person standing to their left or their right, they must get more candies than that neighbor.
To solve this, first start by giving everyone just one candy. Then, walk down the line from the left side to the right side. Every time a child has more stars than the person on their left, give them one more candy than the neighbor has.
After that, walk down the line backwards starting from the right side. If a child has more stars than the person on their right, check to see if they have enough candies. If they have a smaller number of candies than the person on their right, give them one more candy than the neighbor has so they stay happy.
Finally, count up all the candies you have given out in total by adding them together. This ensures every child is happy because they have more than the neighbors they outshine, while keeping the total number of candies as small as possible.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Rust | C# | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | ||||||||
| MemoryLimitExceeded | C++ | Python | |||||||||
| Progiez | C++ | Python | Java | ||||||||
| github | aylei | Rust | |||||||||
| begeekmyfriend | C | ||||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JS | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| aylei | Rust | ||||||||||
| begeekmyfriend | C | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| everthis | JavaScript | ||||||||||
| fpdjsns | C++ | ||||||||||
| gaosq0604 | Python | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| luangong | C++ | ||||||||||
| MacJim | C++ | ||||||||||
| qiyuangong | Python | ||||||||||
| ruoru | Rust | ||||||||||
| shreymehul | C# | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| wisdompeak | C++ | ||||||||||
| yuanliu666 | Kotlin | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 3122: Minimum Number of Operations to Satisfy Conditions
- problem 3142: Check if Grid Satisfies Conditions
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality