hugo-blog/content/posts/2020-04-09-leetcode-the-masseuse-lcci.md
Ching 5ba7024532 feat(content; layouts; static): migrate hexo blog. add new theme fuji.
migrate hexo blog. add new theme fuji.

Signed-off-by: Ching <loooching@gmail.com>
2022-02-07 23:38:40 +08:00

49 lines
1.3 KiB
Markdown

---
title: leetcode-the-masseuse-lcci
date: 2020-04-09 00:35:26
tags:
- leetcode
categories: leetcode
mathjax: true
---
### 面试题 17.16. 按摩师
[题目](https://leetcode-cn.com/problems/the-masseuse-lcci/)
<!--more-->
一开始以为是用递归,想了半天没想出来,偷看了一下答案。答案的思路跟递归类似,假设在当前 $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])$
```python
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
```
这种问题原来有个名字叫[动态规划](https://zh.wikipedia.org/wiki/动态规划),上面推导的方程叫[状态转移方程](https://baike.baidu.com/item/状态转移方程),可以找找资料来看一下。