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:
    
  • 相关阅读:
    Sign in with the app-specific password you generated. If you forgot the app-specific password or need to create a new one, go to appleid.apple.com
    Java Web项目搭建过程记录(struts2)
    微信小程序之菜鸟入门教学(二)
    微信小程序之菜鸟选手入门教学(一)
    html 表单input录入内容校验
    VUE中使用driver.js实现先手引导
    BScroll使用
    VUE使用screenfull实现全屏
    VUE打印功能
    VUE中使用XLSX实现导出excel表格
  • 原文地址:https://www.cnblogs.com/tmortred/p/13234434.html
Copyright © 2011-2022 走看看