动态规划DP 之 抢劫得到最多的财务(只是针对题,别无他意)

题目描述:

A robber is 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.
1. 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.
2. What if all houses are arranged in a circle?

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.
1. 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.

2. What if all houses are arranged in a circle?

解题思路:

我们假设在这条街上有n家店铺,其中P(i)表示第i家店铺的财务数,而OPT(i)可以表示从抢劫开始到第i家店铺为止所抢劫的财务的总数目。

因此,我们可以知道对于第i家店铺,如果获取其中的财务,则有P(i)+OPT(i-2);如果不获取其中的财务,则有OPT(i-1).故而,为了在第i位置获得最大的财务,即有OPT(i)=max(P(i)+OPT(i-2),OPT(i-1)).

Pseudo-code:

OPT(i)
if(i==0)
return 0;
else if(i==1)
return P(1);
else
return OPT=max(P(i)+OPT(i-2),OPT(i-1));
在此题中,时间复杂度为T(n)=o(n);
对于第二题,我们知道在环形中,第一个点和最后一个点是相连接的。因此,如果选择了第一个点,肯定不能选择最后一个点。那么,我们就可以将问题分成两种情况来进行讨论:包含第一个点和不包含第一个点,或者说是不包含第一个点和包含最后一个点。最后我们比较这两种情况,并取值最大者。
OPT_CIRCLE_FIRST(i)//即这种情况是选取第一个开始
if(i==0)
return 0;
else if(i==1)
return P(1);
else
return OPT=max(P(i)+OPT(i-2),OPT(i-1));

OPT_CIRCLE_LAST(i)//即选取最后一个
if(i==1)//因为第一个是0,则最后一个是1肯定不能选。
return 0;
else if(i==2)
return P(2);//0和1之间隔着2
else
return OPT=max(P(i)+OPT(i-2),OPT(i-1));

OPT_CHOOSEN_BEST(n)
FIRST=OPT_CIRCLE_FIRST(n-1);//从第一个开始,则最后一个满足条件的是第n-1个;
LAST= OPT_CIRCLE_LAST(n);//结束为最后一个
return max(FIRST,LAST);








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值