码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: 879. Profitable Schemes

时间:2020-07-04 13:37:37      阅读:57      评论:0      收藏:0      [点我收藏+]

标签:miss   member   art   let   output   sub   another   people   des   

Description

There are G people in a gang, and a list of various crimes they could commit.

The i-th crime generates a profit[i] and requires group[i] gang members to participate.

If a gang 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 P profit, and the total number of gang members participating in that subset of crimes is at most G.

How many schemes can be chosen?  Since the answer may be very large, return it modulo 10^9 + 7.

Example

Input: G = 5, P = 3, group = [2,2], profit = [2,3]
Output: 2
Explanation: 
To make a profit of at least 3, the gang could either commit crimes 0 and 1, or just crime 1.
In total, there are 2 schemes.

Note

1 <= G <= 100
0 <= P <= 100
1 <= group[i] <= 100
0 <= profit[i] <= 100
1 <= group.length = profit.length <= 100

分析

    这道题目虽然是 hard 级别,但是比一般 medium 级别题目要简单。就是一般的 二维 dp,即 dp[g][p]. 关键的优化点是  在 p 大于等于 P 时,不在细分 p 

code

    def profitableSchemes(self, G, P, g, p):
        """
        :type G: int
        :type P: int
        :type group: List[int]
        :type profit: List[int]
        :rtype: int
        """
        dp = [[0 for _ in range(P+1)] for _ in range(G+1)]

        for i, _ in enumerate(p):
            if g[i] > G:
                continue
            for j in range(G, g[i]-1, -1):
                if p[i] >= P:
                    dp[j][P] += sum(dp[j-g[i]])
                else:
                    dp[j][P] += sum(dp[j-g[i]][P-p[i]:])
                for k in range(p[i], P):
                    dp[j][k] += dp[j-g[i]][k-p[i]]

            if p[i] >= P:
                dp[g[i]][P] += 1
            else:
                dp[g[i]][p[i]] += 1

        return sum([d[P] for d in dp])%1000000007
    

总结

Runtime: 668 ms, faster than 100.00% of Python online submissions for Profitable Schemes.
Memory Usage: 13.1 MB, less than 75.00% of Python online submissions for Profitable Schemes.
Next challenges:

Leetcode: 879. Profitable Schemes

标签:miss   member   art   let   output   sub   another   people   des   

原文地址:https://www.cnblogs.com/tmortred/p/13234434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!