- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Profitable Schemes in C++
Suppose there is a gang with G people and a list of various crimes they could commit. The i-th crime generates a profit value profit[i] and requires group[i] gang members to participate.
If a gang member is participating in one crime, that he can't participate in another crime. Now let us define profitable scheme any subset of these crimes that generates at least P profit, and total number of members participating in that subset of crimes is at most G.
We have to find how many schemes can be chosen? The answer may be very large, So return it modulo 10^9 + 7.
So, if the input is like G = 5, P = 3 and group = [2,2], profit = [2,3], then the output will be 2
To solve this, we will follow these steps −
ret := 0
Define one 2D array dp of size (G + 1) x (P + 1)
dp[0, 0] := 1
for initialize k := 0, when k < size of group, update (increase k by 1), do −
p := profit[k], g := group[k]
for initialize i := G - g, when i >= 0, update (decrease i by 1), do −
for initialize j := P, when j >= 0, update (decrease j by 1), do−
dp[i + g, minimum of P and j + p]
dp[i + g, minimum of P and j + p]
for initialize i := 0, when i <= G, update (increase i by 1), do −
ret := ret + dp[i, P]
ret := ret mod m
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; const int m = 1e9 + 7; class Solution { public: int profitableSchemes(int G, int P, vector<int> &group, vector<int> &lprofit) { int ret = 0; vector<vector<int>> dp(G + 1, vector<int>(P + 1)); dp[0][0] = 1; for (int k = 0; k < group.size(); k++) { int p = profit[k]; int g = group[k]; for (int i = G - g; i >= 0; i--) { for (int j = P; j >= 0; j--) { dp[i + g][min(P, j + p)] += dp[i][j]; dp[i + g][min(P, j + p)] %= m; } } } for (int i = 0; i <= G; i++) { ret += dp[i][P]; ret %= m; } return ret; } }; main(){ Solution ob; vector<int> v = {2,2}, v1 = {2,3}; cout << (ob.profitableSchemes(5,3,v, v1)); }
Input
5, 3, [2,2], [2,3]
Output
2