Java Code
Problem Statement
public class StarsAndBars {
// Efficiently calculate nCr to avoid overflow
public static long combinations(int n, int r) {
// n β Total selection set
// r β No. of items to be selected from total sets
// r < 0 β Invalid number of selections
// r > 0 β Eg: Picking up 5 slots from 3 available slots
if (r < 0 || r > n) return 0;
// r == 0 β Choosing no slot (empty set)
// r == n β Choosing all available slots
if (r == 0 || r == n) return 1;
if (r > n / 2) r = n - r; // Optimize: nC3 is easier than nC7
// Using `long` for memory awareness, makes sure the result can be fit in long
// If even long is not enough, use BigInteger
long result = 1;
// Iterate from 1 to the r (number of selected set)
for (int i = 1; i <= r; i++) {
result = result * (n - i + 1) / i;
}
return result;
}
public static void main(String[] args) {
int totalCookies = 10;
int k = 4;
// 1. Global Pre-allocation (each kid gets at least 1) [cite: 54, 68]
int n = totalCookies - k; // 10 - 4 = 6
// 2. Total Baseline: (n + k - 1) choose (k - 1) [cite: 38, 46, 61]
long totalWays = combinations(n + k - 1, k - 1); // 9C3 = 84
// 3. Illegal States (Kid A and Kid B have limit of 2)
// Since they already have 1, the violation is x >= 2 additional cookies. [cite: 71, 81]
int violationShift = 2;
// Illegal A: Pre-allocate violation shift to Kid A [cite: 82, 83]
long illegalA = combinations((n - violationShift) + k - 1, k - 1); // 7C3 = 35
// Illegal B: Pre-allocate violation shift to Kid B
long illegalB = combinations((n - violationShift) + k - 1, k - 1); // 7C3 = 35
// 4. Overlap: Both A and B violate their limits
// Pre-allocate violation to both: n - 2 - 2
long overlap = combinations((n - 2 * violationShift) + k - 1, k - 1); // 5C3 = 10
// 5. Final Result: Total - (A + B) + Overlap
long result = totalWays - (illegalA + illegalB) + overlap;
System.out.println("Valid combinations: " + result); // Output: 24
}
}Time Complexity
Space Complexity
Last updated