2025-06-01 Daily Challenge

Today I have done leetcode's June LeetCoding Challenge with cpp.

June LeetCoding Challenge 1

Description

Distribute Candies Among Children II

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.

 

Example 1:

Input: n = 5, limit = 2
Output: 3
Explanation: There are 3 ways to distribute 5 candies such that no child gets more than 2 candies: (1, 2, 2), (2, 1, 2) and (2, 2, 1).

Example 2:

Input: n = 3, limit = 3
Output: 10
Explanation: There are 10 ways to distribute 3 candies such that no child gets more than 3 candies: (0, 0, 3), (0, 1, 2), (0, 2, 1), (0, 3, 0), (1, 0, 2), (1, 1, 1), (1, 2, 0), (2, 0, 1), (2, 1, 0) and (3, 0, 0).

 

Constraints:

  • 1 <= n <= 106
  • 1 <= limit <= 106

Solution

constexpr long long combinationOfTwo(int total) {
  if(total < 0) return 0;
  return 1LL * total * (total - 1) / 2;
}
class Solution {
public:
  long long distributeCandies(int n, int limit) {
    return combinationOfTwo(n + 2)  
      - 3 * combinationOfTwo(n - limit + 1) 
      + 3 * combinationOfTwo(n - 2 * limit)
      - combinationOfTwo(n - 3 * limit - 1);
  }
};

// Accepted
// 958/958 cases passed (5 ms)
// Your runtime beats 77.06 % of cpp submissions
// Your memory usage beats 18.82 % of cpp submissions (9 MB)