1.3 KiB
1.3 KiB
| title | date | tags | categories | mathjax | |
|---|---|---|---|---|---|
| leetcode-the-masseuse-lcci | 2020-04-09 00:35:26 |
|
leetcode | true |
面试题 17.16. 按摩师
一开始以为是用递归,想了半天没想出来,偷看了一下答案。答案的思路跟递归类似,假设在当前 i 时刻,dp[i][0] 为当前预约不接的情况下最长预约时间,dp[i][1] 则为接受当前预约的最长预约时间。
那很显然,由于不能接受相邻两个预约,dp[i][1] = dp[i-1][0] + nums_i
不接受当前预约的话,上一个预约接不接受都可以,dp[i][0] = max(dp[i-1][0], dp[i-1][1])
最后只要比较两种情况即可 max(dp[i][0], dp[i][1])
class Solution:
def massage(self, nums) -> int:
if not nums:
return 0
n = len(nums)
not_choose = 0
choose = 0
for n in nums:
not_choose, choose = max(not_choose, choose), not_choose+n
return max(not_choose, choose)
# 52 ms 13.6 MB