Category: Memoization

Count of valid arrays of size P with elements in range [1, N] having duplicates at least M distance apart

#include using namespace std;  int calculate(int position, int used, int unused, int P,              int M, vector& dp){        if (position == P) {                        return unused == 0 ? 1 : 0;    }              if (dp[position][used][unused] != -1)        return dp[position][used][unused];          int result = 0;              if (unused > 0) {                        result += calculate(position + 1, used + 1,                            unused – 1, P, M, dp)                  * unused;    }              if (used > M) {                        result += […]

Continue Reading

Maximum number of groups that can receive fresh donuts distributed in batches of size K

import java.io.*;import java.util.*;class GFG {            static HashMap memo;                public static int dfs(int[] V,                          int left, int K)    {                        int q = 0;                                String key = Arrays.toString(V);        key += Integer.toString(left);                if (memo.containsKey(key))            return memo.get(key);                else if (left == 0) {                        for (int i = 1; i < K; ++i)                if (V[i] > 0) {                                        V[i]–;                                                            q = Math.max(                        q, 1 + dfs(V, K – i, K));                                        V[i]++;                }        }                        else {            for (int i = 1; […]

Continue Reading