Candy Distribution
Greedy algorithm to distribute minimum candies ensuring children with higher ratings get more than neighbors.
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
int main() {
cout << "INSTRUCTIONS: Enter the number of children n, followed by n ratings." << endl;
int n;
cin >> n;
vector<int> rating(n), candy(n, 1);
for (int i = 0; i < n; i++) cin >> rating[i];
for (int i = 1; i < n; i++)
if (rating[i] > rating[i - 1])
candy[i] = candy[i - 1] + 1;
for (int i = n - 2; i >= 0; i--)
if (rating[i] > rating[i + 1])
candy[i] = max(candy[i], candy[i + 1] + 1);
cout << accumulate(candy.begin(), candy.end(), 0);
}Candy Distribution — Free C++, C, Python Code Example
Greedy algorithm to distribute minimum candies ensuring children with higher ratings get more than neighbors. This free code example is available in C++, C, Python and can be copied and run immediately — no account or signup required. Use the language tabs above to switch between implementations.
How to Use This Code
- Select your language — click the language tab (C, Java, C++, or Python) above the code viewer.
- Copy the code — use the copy button in the top-right corner of the code block.
- Run it — paste into a file with the correct extension (.c, .java, .cpp, .py), compile, and run using your terminal or IDE.
- Follow the on-screen instructions in the terminal to provide any required inputs.
Frequently Asked Questions
What does this program do?
Greedy algorithm to distribute minimum candies ensuring children with higher ratings get more than neighbors.
Which languages is it available in?
Available in C++, C, Python. Switch between implementations using the tabs at the top of the code viewer.
How do I run this code?
Copy the code, save it with the right file extension (.c, .java, .cpp, or .py), then compile or run it with your installed compiler or interpreter (GCC, JDK, G++, Python 3).
Is this code free?
Yes — free to view, copy, and use. No account required.