15% off all plans & roadmaps Use code
See plansCandy
- LeetCode 135
- Hard
- Greedy Patterns
- Sorting Based
Updated
TL;DR: Give each child at least one candy so that a higher rating beats its neighbors, using as few candies as possible. Scan the line twice, left to right and then right to left, and keep the larger requirement at each child.
Problem
There are n children standing in a line. Each child has a rating value, given in the integer array ratings.
You must give out candies under two rules. Every child gets at least one candy. A child with a higher rating than a neighbor gets more candies than that neighbor.
Return the minimum number of candies you need to satisfy both rules.
Example 1
Input: ratings = [1,0,2] Output: 5 Explanation: Give the first, second and third children 2, 1 and 2 candies.
Example 2
Input: ratings = [1,2,2] Output: 4 Explanation: Give the first, second and third children 1, 2 and 1 candies. The third child gets 1 candy because it meets both rules.
Constraints
n == ratings.length1 <= n <= 2 * 10^40 <= ratings[i] <= 2 * 10^4
Constraints that matter
- n up to 2 * 10^4 makes the O(n^2) repeated-scan method too slow in the worst case, since it can take about n^2 = 4 * 10^8 checks.
- Each child is compared only with its immediate neighbors, so each child has at most two constraints. A fixed sweep in each direction can handle them.
- Ratings can be equal, and equal neighbors impose no rule. The solution must use strict comparisons only.
- Each child needs at most n candies, so the total is at most n^2 = 4 * 10^8. That fits in a 32-bit int, so overflow is not a concern here.
Hints
Hint 1
Each child has a left neighbor and a right neighbor, and each neighbor can force a different requirement.
Hint 2
Start every child at 1 candy.
Solution
Intuition
Each child has a left neighbor and a right neighbor, and each neighbor can force a different requirement. A scan from left to right sees the left side of every child, but it cannot see the right side yet. A scan from right to left has the reverse problem.
Picture a row of buckets, where the candies array is the row and each bucket holds a count of pebbles. Walk left to right topping up each bucket from its left neighbor, then walk back right to left topping up from the right neighbor.
This is a greedy problem with directional passes. Give each child the least candy that satisfies the rules you have checked so far. Each child's requirement depends only on a neighbor with a lower rating, so one sweep per direction settles every child.
The sorting variant takes a different route. If you process children from the lowest rating to the highest, every lower neighbor is final before you read it. That works, but the sort costs O(n log n), and the two sweeps already reach O(n) without it.
To recognise this pattern, look for a constraint that links each item only to its neighbors. When the constraint points one way, a sweep in that direction often settles it.
Worked example
Input: ratings = [1, 3, 2, 1, 2, 1, 5, 4, 3, 2, 1] Output: 25 Explanation: Index 1 has rating 3, higher than both neighbors, so it needs 3 candies. The falling run 5, 4, 3, 2, 1 starting at index 6 forces 5, 4, 3, 2, 1 candies. Every other child needs only what its single higher neighbor forces, so the minimum total is 25.
Approach 1: Brute force: repeat full scans
Start every child at 1 candy. Scan the line, and whenever a child has a higher rating than a neighbor but not more candy, raise that child to one more than the neighbor.
Repeat full scans until one scan changes nothing. Each rule is applied directly, so the result is correct, but the scans can repeat many times.
Steps
- Set
candiesto 1 for every child. - Start a scan from index 0 to n - 1 and set
changedto false. - For child i, if its rating is higher than the left neighbor's and it has no more candy, set it to the left neighbor's count plus one.
- Apply the same check against the right neighbor.
- Set
changedto true each time a count goes up. - Stop when a full scan leaves
changedfalse, then return the sum ofcandies.
Dry run
The example has 11 children, and the ratings are [1, 3, 2, 1, 2, 1, 5, 4, 3, 2, 1].
Pass 1 changes indices 1, 2, 4, 6, 7, 8 and 9. The array ends the pass at [1, 2, 2, 1, 2, 1, 2, 2, 2, 2, 1].
Pass 2 changes indices 1, 6, 7 and 8. The array becomes [1, 3, 2, 1, 2, 1, 3, 3, 3, 2, 1].
Pass 3 changes indices 6 and 7. The array becomes [1, 3, 2, 1, 2, 1, 4, 4, 3, 2, 1].
Pass 4 changes index 6 to 5. The array becomes [1, 3, 2, 1, 2, 1, 5, 4, 3, 2, 1].
Pass 5 changes nothing, so the loop stops. The sum is 25, which matches the example output.
Complexity
| Time | O(n^2) |
|---|---|
| Space | O(n) |
Let n be the number of children. One scan does n constant-time checks. In the worst case, such as a long strictly decreasing run, a raise can ripple one step per scan, so the loop needs about n scans. That gives about n * n checks, which is O(n^2). The candies array holds n integers, so the extra space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
candies = [1] * n
changed = True
while changed:
changed = False
for i in range(n):
# Left rule: a higher rating than the left neighbor needs more candy.
if i > 0 and ratings[i] > ratings[i - 1] and candies[i] <= candies[i - 1]:
candies[i] = candies[i - 1] + 1
changed = True
# Right rule: a higher rating than the right neighbor needs more candy.
if i < n - 1 and ratings[i] > ratings[i + 1] and candies[i] <= candies[i + 1]:
candies[i] = candies[i + 1] + 1
changed = True
return sum(candies)JavaTested in our runner
import java.util.*;
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1);
boolean changed = true;
while (changed) {
changed = false;
for (int i = 0; i < n; i++) {
if (i > 0 && ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) {
candies[i] = candies[i - 1] + 1;
changed = true;
}
if (i < n - 1 && ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
changed = true;
}
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> candies(n, 1);
bool changed = true;
while (changed) {
changed = false;
for (int i = 0; i < n; i++) {
if (i > 0 && ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) {
candies[i] = candies[i - 1] + 1;
changed = true;
}
if (i < n - 1 && ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
changed = true;
}
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
};JavaScriptTested in our runner
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const n = ratings.length;
const candies = new Array(n).fill(1);
let changed = true;
while (changed) {
changed = false;
for (let i = 0; i < n; i++) {
if (i > 0 && ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) {
candies[i] = candies[i - 1] + 1;
changed = true;
}
if (i < n - 1 && ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
changed = true;
}
}
}
return candies.reduce((sum, c) => sum + c, 0);
};GoTested in our runner
func candy(ratings []int) int {
n := len(ratings)
candies := make([]int, n)
for i := range candies {
candies[i] = 1
}
changed := true
for changed {
changed = false
for i := 0; i < n; i++ {
if i > 0 && ratings[i] > ratings[i-1] && candies[i] <= candies[i-1] {
candies[i] = candies[i-1] + 1
changed = true
}
if i < n-1 && ratings[i] > ratings[i+1] && candies[i] <= candies[i+1] {
candies[i] = candies[i+1] + 1
changed = true
}
}
}
total := 0
for _, c := range candies {
total += c
}
return total
}C#Tested in our runner
public class Solution {
public int candy(int[] ratings) {
int n = ratings.Length;
int[] candies = new int[n];
for (int i = 0; i < n; i++) candies[i] = 1;
bool changed = true;
while (changed) {
changed = false;
for (int i = 0; i < n; i++) {
if (i > 0 && ratings[i] > ratings[i - 1] && candies[i] <= candies[i - 1]) {
candies[i] = candies[i - 1] + 1;
changed = true;
}
if (i < n - 1 && ratings[i] > ratings[i + 1] && candies[i] <= candies[i + 1]) {
candies[i] = candies[i + 1] + 1;
changed = true;
}
}
}
int total = 0;
foreach (int c in candies) total += c;
return total;
}
}The Sorting Based infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Sorting Based
Part of Greedy Patterns
Approach 2: Sort, then fix by ratingSorting Based
What is slow: the brute force rescans the whole line because one raise can force a neighbor to rise, and that can cascade. Each scan repeats work that earlier scans already did.
The insight that fixes it is the processing order. A child's constraint only involves neighbors with lower ratings. If you handle children from the lowest rating to the highest, every lower neighbor is final before you read it, so one pass is enough.
Ties need no special handling. Equal neighbors impose no rule, so their order in the sorted list does not matter.
Steps
- Build a list of indices 0 to n - 1 and sort it by
ratings, lowest rating first. - Set
candiesto 1 for every child. - For each index i in sorted order, check the left neighbor. If ratings[i] is higher, set candies[i] to the larger of its current value and candies[i - 1] + 1.
- Apply the same check against the right neighbor.
- Return the sum of
candies.
Dry run
The sorted index order is [0, 3, 5, 10, 2, 4, 9, 1, 8, 7, 6]. The first four children have rating 1, so they keep 1 candy.
Index 2 (rating 2) raises to 2 because its right neighbor has 1 candy. Index 4 raises to 2 from its left neighbor, and index 9 raises to 2 from its right neighbor.
Index 1 (rating 3) raises to 2 from the left and to 3 from the right. Index 8 raises to 3, index 7 (rating 4) raises to 4, and index 6 (rating 5) raises to 5.
The final array is [1, 3, 2, 1, 2, 1, 5, 4, 3, 2, 1], and its sum is 25.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(n) |
Let n be the number of children. Sorting the n indices takes O(n log n) comparisons. The loop visits each index once and does constant work per visit, which adds O(n). The index list and the candies array each hold n values, so the space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
# Process indices from the lowest rating to the highest.
order = sorted(range(n), key=lambda i: ratings[i])
candies = [1] * n
for i in order:
if i > 0 and ratings[i] > ratings[i - 1]:
candies[i] = max(candies[i], candies[i - 1] + 1)
if i < n - 1 and ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)JavaTested in our runner
import java.util.*;
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) {
order[i] = i;
}
// Lowest rating first.
Arrays.sort(order, Comparator.comparingInt(i -> ratings[i]));
int[] candies = new int[n];
Arrays.fill(candies, 1);
for (int i : order) {
if (i > 0 && ratings[i] > ratings[i - 1]) {
candies[i] = Math.max(candies[i], candies[i - 1] + 1);
}
if (i < n - 1 && ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
}C++Tested in our runner
#include <algorithm>
#include <numeric>
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> order(n);
iota(order.begin(), order.end(), 0);
// Lowest rating first.
sort(order.begin(), order.end(), [&](int a, int b) { return ratings[a] < ratings[b]; });
vector<int> candies(n, 1);
for (int i : order) {
if (i > 0 && ratings[i] > ratings[i - 1]) {
candies[i] = max(candies[i], candies[i - 1] + 1);
}
if (i < n - 1 && ratings[i] > ratings[i + 1]) {
candies[i] = max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
};JavaScriptTested in our runner
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const n = ratings.length;
// Indices sorted by rating, lowest first.
const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => ratings[a] - ratings[b]);
const candies = new Array(n).fill(1);
for (const i of order) {
if (i > 0 && ratings[i] > ratings[i - 1]) {
candies[i] = Math.max(candies[i], candies[i - 1] + 1);
}
if (i < n - 1 && ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
return candies.reduce((sum, c) => sum + c, 0);
};GoTested in our runner
import "sort"
func candy(ratings []int) int {
n := len(ratings)
order := make([]int, n)
for i := range order {
order[i] = i
}
// Lowest rating first.
sort.Slice(order, func(a, b int) bool {
return ratings[order[a]] < ratings[order[b]]
})
candies := make([]int, n)
for i := range candies {
candies[i] = 1
}
for _, i := range order {
if i > 0 && ratings[i] > ratings[i-1] && candies[i] < candies[i-1]+1 {
candies[i] = candies[i-1] + 1
}
if i < n-1 && ratings[i] > ratings[i+1] && candies[i] < candies[i+1]+1 {
candies[i] = candies[i+1] + 1
}
}
total := 0
for _, c := range candies {
total += c
}
return total
}C#Tested in our runner
public class Solution {
public int candy(int[] ratings) {
int n = ratings.Length;
// Indices sorted by rating, lowest first.
int[] order = Enumerable.Range(0, n).OrderBy(i => ratings[i]).ToArray();
int[] candies = new int[n];
for (int i = 0; i < n; i++) candies[i] = 1;
foreach (int i in order) {
if (i > 0 && ratings[i] > ratings[i - 1]) {
candies[i] = Math.Max(candies[i], candies[i - 1] + 1);
}
if (i < n - 1 && ratings[i] > ratings[i + 1]) {
candies[i] = Math.Max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
foreach (int c in candies) total += c;
return total;
}
}Approach 3: Two passes, left then rightOptimal
What is slow: sorting costs O(n log n), and the full order it creates is more than the problem needs.
The insight that fixes it: each child's requirement comes from one neighbor at a time. A left-to-right pass settles the left-neighbor rule for every child, because each left neighbor is already final when you reach its right side. A right-to-left pass then settles the right-neighbor rule.
The second pass must keep the larger value. Taking the maximum keeps the left requirement that the first pass set.
Why it is correct. After the left pass, every child with a higher rating than its left neighbor has more candy than that neighbor. The right pass only raises values, and it raises each child to at least its right neighbor plus one when needed, so the left rule still holds. Each value is the smallest that meets every chain of strictly higher neighbors ending at that child, so no child gets more than required.
Steps
- Set
candiesto 1 for every child. - Scan from index 1 to n - 1. If ratings[i] > ratings[i - 1], set candies[i] to candies[i - 1] + 1.
- Scan from index n - 2 down to 0. If ratings[i] > ratings[i + 1], set candies[i] to the larger of candies[i] and candies[i + 1] + 1.
- Return the sum of
candies.
Dry run
The example ratings are [1, 3, 2, 1, 2, 1, 5, 4, 3, 2, 1]. The table shows each check that changes a value. Unchanged children are omitted.
| Step | Index | Check | candies[index] after step |
|---|---|---|---|
| Left 1 | 1 | 3 > 1, so take left + 1 | 2 |
| Left 2 | 2 | 2 is not > 3 | 1 |
| Left 3 | 3 | 1 is not > 2 | 1 |
| Left 4 | 4 | 2 > 1, so take left + 1 | 2 |
| Left 5 | 5 | 1 is not > 2 | 1 |
| Left 6 | 6 | 5 > 1, so take left + 1 | 2 |
| Left 7 | 7 | 4 is not > 5 | 1 |
| Left 8 | 8 | 3 is not > 4 | 1 |
| Left 9 | 9 | 2 is not > 3 | 1 |
| Left 10 | 10 | 1 is not > 2 | 1 |
| Right 9 | 9 | 2 > 1, so max(1, 1 + 1) | 2 |
| Right 8 | 8 | 3 > 2, so max(1, 2 + 1) | 3 |
| Right 7 | 7 | 4 > 3, so max(1, 3 + 1) | 4 |
| Right 6 | 6 | 5 > 4, so max(2, 4 + 1) | 5 |
| Right 5 | 5 | 1 is not > 5 | 1 |
| Right 4 | 4 | 2 > 1, so max(2, 1 + 1) | 2 |
| Right 3 | 3 | 1 is not > 2 | 1 |
| Right 2 | 2 | 2 > 1, so max(1, 1 + 1) | 2 |
| Right 1 | 1 | 3 > 2, so max(2, 2 + 1) | 3 |
| Right 0 | 0 | 1 is not > 3 | 1 |
After the left pass the array is [1, 2, 1, 1, 2, 1, 2, 1, 1, 1, 1]. After the right pass it is [1, 3, 2, 1, 2, 1, 5, 4, 3, 2, 1], and its sum is 25.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the number of children. Each pass does n - 1 constant-time steps, so the two passes total about 2n steps, which is O(n). Neither pass rescans earlier positions, so no work repeats. The candies array holds n values, so the space is O(n).
PythonTested in our runner
from typing import List, Optional
class Solution:
def candy(self, ratings: List[int]) -> int:
n = len(ratings)
candies = [1] * n
# Left to right: enforce the left-neighbor rule.
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1
# Right to left: enforce the right-neighbor rule, keeping the larger value.
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i + 1]:
candies[i] = max(candies[i], candies[i + 1] + 1)
return sum(candies)JavaTested in our runner
import java.util.*;
class Solution {
public int candy(int[] ratings) {
int n = ratings.length;
int[] candies = new int[n];
Arrays.fill(candies, 1);
// Left to right: enforce the left-neighbor rule.
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
// Right to left: enforce the right-neighbor rule, keeping the larger value.
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int candy(vector<int>& ratings) {
int n = ratings.size();
vector<int> candies(n, 1);
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
for (int c : candies) {
total += c;
}
return total;
}
};JavaScriptTested in our runner
/**
* @param {number[]} ratings
* @return {number}
*/
var candy = function(ratings) {
const n = ratings.length;
const candies = new Array(n).fill(1);
for (let i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
for (let i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.max(candies[i], candies[i + 1] + 1);
}
}
return candies.reduce((sum, c) => sum + c, 0);
};GoTested in our runner
func candy(ratings []int) int {
n := len(ratings)
candies := make([]int, n)
for i := range candies {
candies[i] = 1
}
for i := 1; i < n; i++ {
if ratings[i] > ratings[i-1] {
candies[i] = candies[i-1] + 1
}
}
for i := n - 2; i >= 0; i-- {
if ratings[i] > ratings[i+1] && candies[i] < candies[i+1]+1 {
candies[i] = candies[i+1] + 1
}
}
total := 0
for _, c := range candies {
total += c
}
return total
}C#Tested in our runner
public class Solution {
public int candy(int[] ratings) {
int n = ratings.Length;
int[] candies = new int[n];
for (int i = 0; i < n; i++) candies[i] = 1;
for (int i = 1; i < n; i++) {
if (ratings[i] > ratings[i - 1]) {
candies[i] = candies[i - 1] + 1;
}
}
for (int i = n - 2; i >= 0; i--) {
if (ratings[i] > ratings[i + 1]) {
candies[i] = Math.Max(candies[i], candies[i + 1] + 1);
}
}
int total = 0;
foreach (int c in candies) total += c;
return total;
}
}Common mistakes
candies[i] = candies[i + 1] + 1in the right pass, without a max. This overwrites the left requirement. Usemax(candies[i], candies[i + 1] + 1)so the earlier value survives.- Starting
candiesat 0 instead of 1. Every child must get at least one candy, and a valley child that no rule raises stays at 0. Initialise the whole array to 1. - Testing
ratings[i] >= ratings[i - 1]. Equal neighbors then force an extra candy, which inflates the total. Use a strict comparison. - Running only the left-to-right pass. The input
[2, 1]returns 2, but the right child needs 1 and the left child needs 2, so the answer is 3. The right pass is required. - Checking the wrong neighbor in the right pass, for example comparing
ratings[i] > ratings[i - 1]while scanning from the right. Each pass must compare with the neighbor it has already settled. - Writing the update as a recursion that pushes changes to neighbors. With n up to 2 * 10^4, Python can exceed its default recursion limit, and the call count can grow quickly. Use the iterative passes.
Edge cases
[7]: a single child gets 1 candy, so the answer is 1.[5, 5, 5]: equal ratings impose no rule, so every child keeps 1 candy and the answer is 3.[1, 2, 3, 4]: a strictly increasing run gives 1, 2, 3, 4, so the answer is 10.[4, 3, 2, 1]: a strictly decreasing run gives 4, 3, 2, 1, so the answer is 10.[2, 1]: the lower right child stays at 1 and the left child needs 2, so the answer is 3. A left-only pass gets this wrong.[1, 2, 2]: the plateau child gets 1 candy because equal ratings impose no rule, so the answer is 4.
Follow-ups interviewers ask
- Can you solve it in O(1) extra space?
- Yes. Walk the line once and track the length of the current rising run and the current falling run. When a falling run ends, add its candies, and correct the peak if the falling run is longer than the rising run before it. The extra space is a few counters, so it is O(1).
- What if the ratings are strictly increasing or strictly decreasing?
- Then each child needs one more candy than its lower neighbor in the run, so the values are forced to 1 through n. The answer is n(n + 1) / 2 in O(1) time. The two-pass solution still works, but the formula is a fast check.
- Why do you need two passes, and why does one pass fail?
- A child depends on both neighbors, and a single left-to-right pass only sees the left side. The input
[2, 1]shows the failure, since the left child needs a value that the first pass never sets. The second pass reads the right side using the first pass's values, and the maximum keeps both rules.
Candy FAQ
What is the time complexity of Candy?
The two-pass solution runs in O(n) time, because it makes two linear scans. The sorting solution runs in O(n log n) because of the sort. The brute force repeated-scan solution runs in O(n^2) in the worst case.
Why use two passes for Candy?
Each child's requirement depends on its left neighbor and its right neighbor. One pass handles each side, and the maximum of the two results satisfies both. Each child gets the least candy that meets the rules, which is the greedy choice.
Can Candy be solved in O(1) extra space?
Yes. A single pass that tracks rising and falling run lengths uses only a few counters. The two-pass array version is easier to get right under time pressure, but the counter version is the strict O(1) answer.
Why does the sorting approach work for Candy?
Sorting by rating means every neighbor with a lower rating is processed first. Its candy count is final when you read it, so one pass is enough. Equal ratings impose no rule, so their order in the sorted list does not matter.
Why does the brute force approach repeat passes?
Raising one child can force a neighbor to rise, and that can force another neighbor. A single scan may not reach the end of a chain. The scan repeats until a full pass changes nothing.
Asked at
See which companies ask this — Pro
Related problems
- Hand of Straights · same technique: Sorting Based
- Merge Triplets to Form Target Triplet · same technique: Sorting Based
- Sort an Array · same technique: Sorting Based
- Two City Scheduling · same technique: Sorting Based
- Queue Reconstruction by Height · same technique: Sorting Based
- Employee Free Time · same pattern: Greedy Patterns
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns