Skip to main content
Back to problems
Leetcode
Medium
Math
Combinatorics
Arrays
Distribute Candies Among Children II

Count the number of ways to distribute exactly n candies among 3 children with per-child upper bounds.

Acceptance 100%
Problem Statement

Problem

You are given an integer n representing the total number of candies, and three non-negative integers limit1, limit2, and limit3 representing the maximum candies each of the 3 children can receive.

Count how many different ways you can distribute all n candies among the children such that:

  • each child receives a non-negative integer number of candies,
  • the total number of candies distributed is exactly n,
  • child i receives at most limiti candies.

Two distributions are different if at least one child receives a different number of candies.

Notes

  • The children are distinct.
  • Candy counts are integers.
  • You must use all candies.

Input Format

  • A single line or structured input containing three limits and the total number of candies.
  • Conceptually: n, limit1, limit2, limit3.

Output Format

  • Return the number of valid distributions as an integer.

Constraints

  • 0 <= n
  • 0 <= limit1, limit2, limit3
  • The answer fits in a standard integer type for the platform version of the problem.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 5, limit1 = 2, limit2 = 2, limit3 = 2

Output

3

Explanation

The valid distributions are (1,2,2), (2,1,2), and (2,2,1).

Example 2

Input

n = 3, limit1 = 1, limit2 = 1, limit3 = 1

Output

1

Explanation

Only (1,1,1) uses all 3 candies without exceeding any limit.

Show 1 more example

Example 3

Input

n = 4, limit1 = 0, limit2 = 2, limit3 = 3

Output

1

Explanation

Child 1 must receive 0, and the remaining 4 candies must be split as (1,3) between the other two children, which is the only valid distribution.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.