Skip to main content
Back to problems
#2928
Easy Algorithms

Distribute candies among children i

Math Combinatorics Enumeration
76.2% acceptance
Feb 25, 2026
151
74
You are given two positive integers n and limit. Return the total number of ways to distribute n candies among 3 children such that no child gets more than limit candies.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn distribute_candies(n: i32, limit: i32) -> i32 {
    let mut count = 0i32;
    for a in 0..=limit {
      for b in 0..=limit {
        let c = n - a - b;
        if c >= 0 && c <= limit {
          count += 1;
        }
      }
    }
    count
  }
}