Candy Distribution
Distribute the minimum number of candies to children such that: (1) each child gets at least one candy, and (2) children with higher ratings than their neighbors get more candies. The elegant two-pass greedy algorithm ensures both left and right neighbor constraints are satisfied independently, then combines them. Classic problem demonstrating multi-pass greedy strategy.
Visualization
Interactive visualization for Candy Distribution
Interactive visualization with step-by-step execution
Implementation
1function candy(ratings: number[]): number {
2 const n = ratings.length;
3 const candies = new Array(n).fill(1);
4
5 for (let i = 1; i < n; i++) {
6 if (ratings[i] > ratings[i-1]) {
7 candies[i] = candies[i-1] + 1;
8 }
9 }
10
11 for (let i = n - 2; i >= 0; i--) {
12 if (ratings[i] > ratings[i+1]) {
13 candies[i] = Math.max(candies[i], candies[i+1] + 1);
14 }
15 }
16
17 return candies.reduce((a, b) => a + b, 0);
18}Deep Dive
Theoretical Foundation
Candy Distribution requires satisfying local constraints (higher rating → more candy than neighbors) while minimizing total. Key insight: handle left and right neighbor constraints independently. First pass (left-to-right): if rating[i] > rating[i-1], give candies[i] = candies[i-1] + 1. Second pass (right-to-left): if rating[i] > rating[i+1], ensure candies[i] >= candies[i+1] + 1 by taking max. After two passes, all constraints satisfied with minimum candies. Time: O(n) two passes. Space: O(n) for candies array. This demonstrates greedy approach handling bidirectional constraints.
Complexity
Time
O(n)
O(n)
O(n)
Space
O(n)
Applications
Industry Use
Fair resource distribution with constraints
Salary allocation based on performance
Bonus distribution in organizations
Reward systems in games
Grade curve adjustment
Use Cases
Related Algorithms
Huffman Coding
Huffman Coding is a lossless data compression algorithm that creates optimal prefix-free variable-length codes based on character frequencies. Developed by David A. Huffman in 1952 as a student at MIT, it uses a greedy approach to build a binary tree where frequent characters get shorter codes. This algorithm is fundamental in ZIP, JPEG, MP3, and many compression formats.
Activity Selection Problem
Select the maximum number of non-overlapping activities from a set, where each activity has a start and end time. This classic greedy algorithm demonstrates the greedy choice property: always selecting the activity that finishes earliest leaves the most room for remaining activities. Used in scheduling problems, resource allocation, and interval management. Achieves optimal solution with O(n log n) time complexity.
Fractional Knapsack Problem
Given items with values and weights, and a knapsack with capacity, select items (or fractions thereof) to maximize total value. Unlike the 0/1 knapsack where items must be taken whole, the fractional knapsack allows taking fractions of items. The greedy approach of taking items in order of value-to-weight ratio yields the optimal solution in O(n log n) time. This demonstrates when greedy algorithms work vs. when dynamic programming is needed.
Job Sequencing with Deadlines
Schedule jobs with deadlines and profits to maximize total profit. Each job takes 1 unit time and has a deadline and profit. The greedy strategy is to sort jobs by profit (descending) and greedily schedule each job as late as possible before its deadline. This maximizes profit while respecting constraints. Used in task scheduling, CPU job management, and project planning.