题目描述:
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?
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: