1. Brute Force — Iterative Conflict Resolution
Intuition
Start with 1 candy per child. Loop over the array repeatedly: if ratings[i] > ratings[i-1] and candies[i] <= candies[i-1], increase candies[i]. If ratings[i] > ratings[i+1] and candies[i] <= candies[i+1], increase candies[i]. Repeat until a full pass makes zero updates.
When to apply: When N <= 50.
Algorithm
- Step 1: Initialize candies array of size N with all 1s.
- Step 2: Loop hasChanged = true.
- Step 3: While hasChanged: set hasChanged = false. For each i, check left and right neighbor constraints. If violated, update candies[i] and set hasChanged = true.
- Step 4: Sum all elements in candies and return.
#include <iostream>#include <vector>#include <numeric> 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; } } } return accumulate(candies.begin(), candies.end(), 0); }}; int main() { Solution sol; vector<int> ratings = {1, 0, 2}; cout << "Min candies: " << sol.candy(ratings) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— Strictly decreasing rating sequence causes O(N) passes of length N, taking O(N2) total operations. - Space complexity:
O(N)— Candies array of size N.
Why Brute Force Doesn't Scale:
A descending ladder of 20,000 ratings takes 20,000 passes, reaching 4 * 108 operations. The two-pass O(N) solution runs in < 5ms.
For N = 20,000: Two-Pass O(N) requires exactly 40,000 operations, executing in ~2ms.