#879

Profitable Schemes

Hard
ArrayDynamic ProgrammingDynamic ProgrammingCombinatorial Optimization
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^m * m)
O(m * n * minProfit)
Space
O(1)
O(minProfit)
💡

Intuition

Time O(m * n * minProfit)Space O(minProfit)

The optimal solution uses dynamic programming to keep track of the number of ways to achieve different profits with a limited number of members. This approach avoids the need to generate all subsets and instead builds up the solution incrementally.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[j] represents the number of ways to achieve profit j with the current number of members.
  2. 2Step 2: For each crime, iterate backwards through the DP array and update the number of ways to achieve profits based on the current crime's profit and required members.
  3. 3Step 3: Sum all the ways to achieve at least minProfit while ensuring the total members used do not exceed n.
solution.py13 lines
1# Full working Python code
2
3def profitableSchemes(n, minProfit, group, profit):
4    MOD = 10**9 + 7
5    dp = [0] * (minProfit + 1)
6    dp[0] = 1  # 1 way to achieve 0 profit
7    for i in range(len(group)):
8        g = group[i]
9        p = profit[i]
10        for j in range(minProfit, -1, -1):
11            for k in range(n, g - 1, -1):
12                dp[j] = (dp[j] + dp[max(0, j - p)]) % MOD
13    return sum(dp) % MOD

Complexity note: The time complexity is O(m * n * minProfit) because we iterate through each crime (m), each possible number of members (n), and each profit level (minProfit). The space complexity is O(minProfit) as we only need to store the ways to achieve profits up to minProfit.

  • 1Dynamic programming is powerful for problems involving combinations and constraints.
  • 2Understanding how to build solutions incrementally can save time and resources.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.