本篇进一步介绍动态规划的基本应用。
1
题目
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
相邻房子不能同时偷,求在此约束下,偷n个房子获益的最大值。
2
分析
分析以下例子:
房子编号:0 1 2 3 4 5
房子收益:4 2 8 6 1 3
目标:偷n个房子获益的最大值。
约束条件:相邻房子不能同时偷。
可能的操作序列:
0 2 4
0 2 5
0 3 5
1 3 5
1 4
小偷面对编号为 i 的房子时,他会有两种决策:
1) 偷(暗含着前一个房子没偷)
2)不偷(注意不一定暗含着前一个房子一定偷了,如果想成前一个房子一定要偷,这就表示偷房子的序列为间隔性的能偷的最大钱数,这是不一定的,比如:3,2,2,3,最大收益为6,中间隔了两个房子!)
如何做决策?
分别比较下这两种决策下的最大能偷的钱数:
1)偷 i,能获得收益为: maxval = num[i] + premax,其中 premax 表示前一个房子没偷能拿到的最大钱数;
2)不偷 i,能获得最大收益为:premax 和前一个房子偷了能获得最大收益,的最大值,即 premax = max(premax, maxval),需要注意:
前一个房子偷了能获得最大收益 为上一步的maxval(它就是表示偷了 i,所以需要用一个临时变量存储起来,供下一个时步用)
可以看到这两种情况相互耦合
1)的premax实际上是上一时步 2)的premax
2)的maxval实际上是上一时步 1)的maxval
最后一步,遍历结束后,取 maxval和premax的最大值
3
代码
python代码,代码很简单,就几行,但是里面暗含的意义都非常大。
premax, maxval = 0,0 for val in nums: tmp = maxval maxval = val + premax premax = max(premax,tmp) return max(premax,maxval)
本文分享自 程序员郭震zhenguo 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有