source: https://leetcode.com/problems/profitable-schemes/description/
Profitable Schemes
There is a group of n members, and a list of various crimes they could commit. The ith crime generates a profit[i] and requires group[i] members to participate in it. If a member participates in one crime, that member can’t participate in another crime.
Let’s call a profitable scheme any subset of these crimes that generates at least minProfit profit, and the total number of members participating in that subset of crimes is at most n.
Return the number of schemes that can be chosen. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: n = 5, minProfit = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation: To make a profit of at least 3, the group could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.
Example 2:
Input: n = 10, minProfit = 5, group = [2,3,5], profit = [6,7,8]
Output: 7
Explanation: To make a profit of at least 5, the group could commit any crimes, as long as they commit one.
There are 7 possible schemes: (0), (1), (2), (0,1), (0,2), (1,2), and (0,1,2).
Constraints:
- 1 <= n <= 100
- 0 <= minProfit <= 100
- 1 <= group.length <= 100
- 1 <= group[i] <= 100
- profit.length == group.length
- 0 <= profit[i] <= 100
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
class Solution { public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { int[][][] memo = new int[102][102][102]; for(int[][] a: memo){ for(int[] b: a){ Arrays.fill(b, -1); } } return dfs(n, minProfit, group, profit, 0, 0, memo); } private static final int MOD = 1_000_000_007; private int dfs(int n, int minProfit, int[] group, int[] profit, int currProfit, int i, int[][][] memo){ //if n < 0, number of member in a group is -ve, return 0 if(n<0) return 0; //if the i == group.length, check if the currProfit >= minProfit, if yes return 1, otherwise 0 if(i==group.length){ if (currProfit >= minProfit){ return 1; } return 0; } //if the value already exists in the memo table if(memo[n][currProfit][i]!=-1) return memo[n][currProfit][i]; int count = 0; //you can either commit a crime //Math.min(minProfit, currProfit+profit[i]) -> currProfit 100 or greater, in both the cases //condition is getting satisfied. count = (count + dfs(n-group[i], minProfit, group, profit, Math.min(minProfit, currProfit+profit[i]), i+1, memo))%MOD; //or you can skip it count = (count + dfs(n, minProfit, group, profit, currProfit, i+1, memo))%MOD; memo[n][currProfit][i] = count; return count; } } |