**
字节教育中台DATA-EDU 后端开发一面算法:
**
原题来自牛客网:
https://www.nowcoder.com/practice/269b4dbd74e540aabd3aa9438208ed8d?tpId=188&tqId=38344&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high-week%2Fquestion-ranking&tab=answerKey
牛客原题网址
描述
给你一个数组,其长度为 n ,在其中选出一个子序列,子序列中任意两个数不能有相邻的下标(子序列可以为空)
本题中子序列指在数组中任意挑选若干个数组成的数组。
**
题解:
**
可以参考leetcode打家劫舍问题https://leetcode-cn.com/problems/house-robber/
打家劫舍leetcode原题
具体思路就是:
我的代码:
class Solution:
def subsequence(self , n: int, array: List[int]) -> int:
# write code here
if len(array) == 0:
return
n = len(array)
dp = [0]*(n+1)
dp[0] = 0
dp[1] = max(array[0],dp[0])
for k in range(2, n+1):
dp[k] = max(dp[k-1], array[k-1]+dp[k-2])
return dp[n]