|
| 1 | +/** |
| 2 | + * 879. Profitable Schemes |
| 3 | + * https://leetcode.com/problems/profitable-schemes/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * There is a group of n members, and a list of various crimes they could commit. The ith crime |
| 7 | + * generates a profit[i] and requires group[i] members to participate in it. If a member |
| 8 | + * participates in one crime, that member can't participate in another crime. |
| 9 | + * |
| 10 | + * Let's call a profitable scheme any subset of these crimes that generates at least minProfit |
| 11 | + * profit, and the total number of members participating in that subset of crimes is at most n. |
| 12 | + * |
| 13 | + * Return the number of schemes that can be chosen. Since the answer may be very large, return |
| 14 | + * it modulo 109 + 7. |
| 15 | + */ |
| 16 | + |
| 17 | +/** |
| 18 | + * @param {number} n |
| 19 | + * @param {number} minProfit |
| 20 | + * @param {number[]} group |
| 21 | + * @param {number[]} profit |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var profitableSchemes = function(n, minProfit, group, profit) { |
| 25 | + const MOD = 1e9 + 7; |
| 26 | + const dp = Array.from({ length: group.length + 1 }, () => |
| 27 | + Array.from({ length: n + 1 }, () => new Array(minProfit + 1).fill(0)) |
| 28 | + ); |
| 29 | + |
| 30 | + dp[0][0][0] = 1; |
| 31 | + |
| 32 | + for (let crime = 1; crime <= group.length; crime++) { |
| 33 | + const membersNeeded = group[crime - 1]; |
| 34 | + const profitGained = profit[crime - 1]; |
| 35 | + |
| 36 | + for (let members = 0; members <= n; members++) { |
| 37 | + for (let currentProfit = 0; currentProfit <= minProfit; currentProfit++) { |
| 38 | + dp[crime][members][currentProfit] = dp[crime - 1][members][currentProfit]; |
| 39 | + |
| 40 | + if (members >= membersNeeded) { |
| 41 | + const prevProfit = Math.max(0, currentProfit - profitGained); |
| 42 | + dp[crime][members][currentProfit] = (dp[crime][members][currentProfit] |
| 43 | + + dp[crime - 1][members - membersNeeded][prevProfit]) % MOD; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + let result = 0; |
| 50 | + for (let members = 0; members <= n; members++) { |
| 51 | + result = (result + dp[group.length][members][minProfit]) % MOD; |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | +}; |
0 commit comments