We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Construct the Array
Construct the Array
Sort by
recency
|
165 Discussions
|
Please Login in order to post a comment
public static long countArray(int n, int k, int x) { long mode = 1000000000 + 7; long[][] dp = new long[n + 1][2]; if (n == 2) { if (x == 1) return 0; else return 1; } if (x != 1) { dp[2][0] = 1; dp[2][1] = k - 2; } else { dp[2][0] = 0; dp[2][1] = k - 1; } for (int i = 3; i <= n; i++) { dp[i][0] = dp[i - 1][1] % mode; dp[i][1] = (dp[i - 1][1] * (k - 2) + dp[i - 1][0] * (k - 1)) % mode; }
I don't know where this code is wrong. I modularized it, but the answer is different.
For an O(n) time and O(1) space complexity, we can think of this problem as keeping track of the total combinations depending on whether we placed an X value previously or we didn't (from n = 3 to n - 2). At n = 2, we either had [1,X] or [1, not X and not 1] if X != 1, or [1,1] and [1, not 1] if X = 1; this gives us combinations of 1 and (k - 2) respectively for the X != 1 case, and 0 and (k - 1) respectively for the X = 1 case. For the iterations from 3 to n - 2, we need to update the “previous was not X” and the “previous was X” combination values. If the previous value was not X, we have two choices: place an X or don’t. If we place an X, the total combinations have not changed, therefore the new “previous was X” is just the previous “previous was not X” value. If we don’t place an X and the previous was not X, the new “previous was not X” combinations are multiplied by (k-2), since we can’t place the previous number either. Finally, we have the case where the previous was X and we don’t place an X. There are (k-1) options, so we multiply the “previous was X” value by (k-1) and add it to the new “previous was not X” value. At n - 1 position, we can never place an X. So if the n - 2 spot was an X, we have (k-1) options and if not, we have (k-2) options. Therefore, our final result will be: “previous was X” times (k-1) + “previous was not X” times (k-2). Not dynamic programming really, but intuitively makes sense. See Java solution below.
Hello,
For me the same solution is passing in python but failing in Scala, can someone help me debug it?
JAVA: --> public static final int MOD = 1000000007; static long[][] memo; static int x, n, k;