小红书:秋招算法笔试 第二题

 
给一个数组 表示点赞的帖子, 要求求不相连的 点赞次数最大,输出 点赞总数 和  贴子数

if __name__ == "__main__":
    n = int(input())
    zan = [int(x) for x in input().strip().split(' ')]
    dp = [[0 for _ in range(2)] for _ in range(n)]
    dp[0][0] = 0
    dp[0][1] = zan[0]
    state_0 = []
    state_1 = [zan[0]]
    for i in range(1, n):
        if dp[i-1][1] > dp[i-1][0]:
            dp[i][0] = dp[i-1][1]
            tem = state_0
            state_0 = state_1
            dp[i][1] = dp[i-1][0] + zan[i]
            state_1 = tem
            state_1.append(zan[i])
        else:
            dp[i][0] = dp[i-1][0]
            dp[i][1] = dp[i-1][0]+zan[i]
            state_1 = state_0[:]
            state_1.append(zan[i])
    if dp[n-1][0] > dp[n-1][1]:
        tol = dp[n-1][0]
        res = len(state_0)
    else:
        tol = dp[n-1][1]
        res = len(state_1)
    # print(state_0)
    # print(state_1)
    print(tol, res)


#小红书##秋招##笔试题目#
全部评论
leetcode题变形
点赞 回复
分享
发布于 2019-08-19 12:47
不需要考虑点赞数为0吗
点赞 回复
分享
发布于 2019-08-20 07:45
滴滴
校招火热招聘中
官网直投
一维数组就可以了 def most_love(n ,love_lst):     num_lst = [1 for i in range(n)]     if n > 2:         love_lst[2] += love_lst[0]         num_lst[2] = 2     for i in range(3, n):         if love_lst[i-2] > love_lst[i-3]:             love_lst[i] += love_lst[i-2]             num_lst[i] = num_lst[i-2] + 1         else:             love_lst[i] += love_lst[i-3]             num_lst[i] = num_lst[i-3] + 1     if love_lst[-1] > love_lst[-2]:         return love_lst[-1], num_lst[-1]     else:         return love_lst[-2], num_lst[-2] if __name__ == "__main__":     n = int(input())     love_lst = list(map(int, input().split()))     best_love, best_num = most_love(n, love_lst)     print(" ".join(map(str,[best_love, best_num])))
点赞 回复
分享
发布于 2019-08-20 10:16

相关推荐

点赞 3 评论
分享
牛客网
牛客企业服务