Monday, November 27, 2023

There are n red balls and m blue balls Find no of arrangements of balls in which not more than k balls of same color are placed next to each other in Java | Hackerrank | LeetCode

public class BallArrangements {
public static int countArrangements(int n, int m, int k) {
int[][][] dp = new int[n + 1][m + 1][k + 1];

// Initialize base cases
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
dp[i][j][0] = 1;
}
}

// Fill the dp array
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
for (int l = 1; l <= k; l++) {
// If we place a red ball at position i
dp[i][j][0] += dp[i - 1][j][l];

// If we place a blue ball at position j
dp[i][j][0] += dp[i][j - 1][l];

// If we place a red ball at position i and there are less than k reds
dp[i][j][l] += dp[i - 1][j][l - 1];

// If we place a blue ball at position j and there are less than k blues
dp[i][j][l] += dp[i][j - 1][l - 1];
}
}
}

int totalArrangements = 0;
for (int l = 0; l <= k; l++) {
totalArrangements += dp[n][m][l];
}

return totalArrangements;
}

public static void main(String[] args) {
int n = 3; // Number of red balls
int m = 2; // Number of blue balls
int k = 1; // Maximum consecutive balls of the same color allowed
int arrangements = countArrangements(n, m, k);
System.out.println("Total arrangements: " + arrangements);
}
}


 

No comments:

Post a Comment