zoukankan      html  css  js  c++  java
  • Leetcode: 879. Profitable Schemes

    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:
    
  • 相关阅读:
    Hibernate总结(二)---hibernate中的各种映射
    调度子系统7_负载均衡(四)
    (网络层: 二 ) 网络层提供的服务(基于无连接的服务)
    我的2013——一名计算机教师的高开低走
    文艺小青年
    图解RabbitMQ
    解决Mac下idea运行速度慢
    较主流的消息队列的比较与选型
    Ubuntu下RabbitMQ安装
    linux守护进程与&的区别
  • 原文地址:https://www.cnblogs.com/tmortred/p/13234434.html
Copyright © 2011-2022 走看看