For an array of length n, a function is defined as f(A) = Number of partitions of A such that each consecutive segment in the partition has a sum in range[L, R] You need to find the expected value of f(A) ie (E|f(A)|) over all arrays of length in having each element an integer in range [1,K] "Here partition means a division of an array into consecutive segments such that each element belongs to exactly one segment Print the expected value for all in the range [1, N] modulo 998244353 Function description Complete the solve function. This function takes the following 4 parameters and returns the array of size N representing the expected value for all n in the range [1, N] modulo 998244353:
• Represents an integer K Represents an integer Represents the lower limit of the range R. Represents the upper East of the range Input format for custom testing The first line contains 4 space- separated integers N, K, L, R Output format Print N Integers space-separated where number denotes the answer for array length.
Constraints
1 <= N <= 10 ^ 5
1 <= K <= 10 ^ 4
1 <= L <= R <= K
Input 2 2 1 2
Output 1 748683266
Link to question: https://www.chegg.com/homework-help/questions-and-answers/partition-expectation-array-length-n-function-defined-f-number-partitions-consecutive-segm-q123298843
1 Like
import java.util.Arrays;
public class ExpectedValuePartitions {
private static final long MOD = 998244353L;
public static long[] solve(int N, int K, int L, int R) {
// Initialize DP tables
long[][] dp = new long[N + 1][K + 1];
long[][] partitionCounts = new long[N + 1][K + 1];
// Base case: single element array
for (int k = 1; k <= K; k++) {
if (L <= k && k <= R) {
dp[1][k] = 1L;
partitionCounts[1][k] = 1L;
}
}
// Fill DP tables for array lengths from 2 to N
for (int n = 2; n <= N; n++) {
for (int k = 1; k <= K; k++) {
if (L <= k && k <= R) {
dp[n][k] = dp[n - 1][k];
partitionCounts[n][k] = partitionCounts[n - 1][k];
for (int prevK = 1; prevK < k; prevK++) {
if (L <= prevK && prevK <= R) {
dp[n][k] = (dp[n][k] + (dp[n - 1][prevK] * partitionCounts[n - 1][k]) % MOD) % MOD;
partitionCounts[n][k] = (partitionCounts[n][k] + partitionCounts[n - 1][k]) % MOD;
}
}
}
}
}
// Calculate expected value for each array length
long[] expectedValues = new long[N + 1];
for (int n = 1; n <= N; n++) {
long totalPartitions = 0L;
for (int k = 1; k <= K; k++) {
if (L <= k && k <= R) {
totalPartitions += dp[n][k];
}
}
long expectedValue = 0L;
for (int k = 1; k <= K; k++) {
if (L <= k && k <= R) {
expectedValue = (expectedValue + ((dp[n][k] * partitionCounts[n][k]) / totalPartitions) % MOD) % MOD;
}
}
expectedValues[n] = expectedValue;
}
return expectedValues;
}
public static void main(String[] args) {
int N = 2, K = 2, L = 1, R = 2;
long[] expectedValues = solve(N, K, L, R);
System.out.println(Arrays.toString(expectedValues));
}
}
your code produc this :
[0, 0, 1]
correct output:
1 748683266