Ride-hailing app~35 min2s · 256 MBtarget O(n × D × P) time, O(D × P) spaceclassic twin: lc-879knapsack
A ride-hailing app plans campaigns for a pool of drivers. Each campaign needs a fixed number of drivers for the day and earns a known profit. A driver can join only one campaign.
A scheme is any set of campaigns, including the empty set. The team lead wants to know how many schemes use at most the available drivers and earn at least a target profit.
Write count_profitable_plans(drivers, min_profit, needs, profits).
drivers is the number of drivers available.min_profit is the profit the scheme must reach, which may be 0.needs[i] and profits[i] are the drivers that campaign i needs and the profit it earns.drivers and whose profits add up to at least min_profit, modulo 1,000,000,007.Input: drivers = 4, min_profit = 4, needs = [2, 1, 2], profits = [3, 2, 1]
Output: 2Let ways[j][k] count the schemes of the campaigns read so far that use exactly j drivers and earn k, where any profit above 4 counts as 4. The empty scheme gives ways[0][0] = 1. For each campaign, run j downwards, and add ways[j - need][k] to ways[j][min(4, k + profit)]. After the three campaigns the table is:
| drivers \ profit | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 | 1 | 0 | 0 | 0 | 0 |
| 1 | 0 | 0 | 1 | 0 | 0 |
| 2 | 0 | 1 | 0 | 1 | 0 |
| 3 | 0 | 0 | 0 | 1 | 1 |
| 4 | 0 | 0 | 0 | 0 | 1 |
The schemes that earn at least 4 are in the last column. Adding it over the rows gives 2.
Input: drivers = 5, min_profit = 3, needs = [2, 2], profits = [2, 3]
Output: 2The schemes {campaign 1, campaign 2} and {campaign 2} earn at least 3 and use at most 4 drivers.
Input: drivers = 2, min_profit = 0, needs = [3], profits = [4]
Output: 1The campaign needs 3 drivers, so only the empty scheme fits, and it earns 0, which meets the target.
1 ≤ drivers ≤ 1000 ≤ min_profit ≤ 1001 ≤ len(needs) = len(profits) ≤ 1001 ≤ needs[i] ≤ 100 and 0 ≤ profits[i] ≤ 100A table with one cell for each driver count and each capped profit has about 101 × 101 = 10,201 cells. Each campaign updates it once. That is about a million small steps. The number of schemes can be as large as 2^100, so counting them one by one is impossible.