【问题标题】:what is wrong with this DP solution?这个 DP 解决方案有什么问题?
【发布时间】:2017-04-24 08:47:36
【问题描述】:

这是一个hackerrank 问题: Alice 是一名幼儿园老师。她想给班上的孩子们一些糖果。所有的孩子排成一排(他们的位置是固定的),每个孩子都根据他或她在课堂上的表现打分。 Alice 想给每个孩子至少 1 颗糖果。如果两个孩子坐在一起,那么评分较高的孩子必须得到更多的糖果。爱丽丝想省钱,所以她需要尽量减少给孩子们的糖果总数。

n = int(input())
candies = 1
candy = 1
temp = int(input())
for i in range(1,n):
    temp1 = int(input())
    if (temp1>temp):
        candy = candy + 1        
    else:
        candy = 1

    temp = temp1
    candies = candies+candy 
    print candy

print candies 

测试数组:n = 10,n 个元素为 [ 2 4 2 6 1 7 8 9 2 1]。我得到 18 作为答案,而 19 是正确答案。我正在做一些我无法理解的错误。

这是完成问题的链接 [https://www.hackerrank.com/challenges/candies]

【问题讨论】:

  • 在您的解决方案中,前两个孩子只收到一个糖果,不是吗?但是10分的孩子应该得到更多。
  • @Flurin - 哦,我的错了。我已经更新了这个问题。 10 是不属于数组的元素数。
  • 好的,那么问题就在最后:9, 2, 1。代码会给得分为 9 的孩子 3 颗糖果。然后给得分为 2 的孩子 一个 糖果,给最后一个孩子 one。得分为 2 的孩子应获得 2 个糖果。
  • 如果两个孩子坐在一起并且分数相同会怎样?您可能会给一个多个糖果,而下一个只给一个 1。这是故意的吗?
  • @Flurin - 我的代码会给 4 个糖果给 9。但是是的 2[location 9] 应该得到 2 个糖果,而我的代码给它一个糖果。如果两者的分数相同,那么下一个应该根据下一个给他得到糖果,不一定是一个,这是代码的问题。

标签: python algorithm dynamic-programming


【解决方案1】:

像这样修改你的代码。您仅从左侧方向进行迭代,但还应检查右侧邻居。也从右边运行相同的循环并取这两个值中的最大值。这应该是你的新糖果任务。

        n = int(input())
        candy = 1
        temp = int(input())
        list =[]
        rating =[]
        rating.append(temp)
        list.append(candy)
        for i in range(1,n):
            temp1 = int(input())
            rating.append(temp1)
            if (temp1>temp):
                candy = candy + 1        
            else:
                candy = 1
            list.append(candy)
            temp = temp1

        rating= rating[::-1]
        list = list[::-1]
        temp = rating[0]
        candies =list[0]
        for i in range(1,n):
            temp1 = rating[i]
            if (temp1>temp):
                list[i]= max(list[i-1]+1,list[i])

            candies =candies+list[i]
            temp = temp1

        print candies

【讨论】:

  • 感谢您的解决方案。从落后开始,然后最大化价值是关键思想。我根本没想过。 DP新手。
【解决方案2】:
    n = input()
    a = [input() for _ in xrange(n)]
   //min. candies he has to give  
    candies = [1] * n

        for i in xrange(1, n):
            if a[i] > a[i-1]:
                candies[i] = candies[i-1] + 1

        for i in xrange(n-2, -1, -1):
            if a[i] > a[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)

        print sum(candies)

我就是这样做的,在开始时给每个孩子一颗糖果。

【讨论】:

  • 感谢您的解决方案。我知道我在哪里做错了。
猜你喜欢
  • 1970-01-01
  • 2021-01-10
  • 2021-02-26
  • 2021-10-14
  • 2021-01-17
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多