Redaksiya
Let’s number the houses starting from the first index (the -th house contains money). Let be the maximum amount of loot after robbing houses from to the -th.
Then .
When computing , consider two cases:
If the -th house is robbed, then the -th house cannot be robbed. In this case, the profit will be .
if the -th house is not robbed, the profit will be .
Thus,
Let's store the values of in the array . The answer to the problem will be the value .
Example
Let's consider the computation of . If we don't rob the -rd house, the profit will be . If the -rd house is robbed, we can rob the first house, gaining a profit of , plus the profit from robbing the -rd house, which is (the total profit will be ).
Now, let's consider the computation of . If we don't rob the -th house, the profit will be . If the -th house is robbed, we can rob the first two houses, gaining a profit of , plus the profit from robbing the -th house, which is (the total profit will be ).
Exercise
Compute the values of for the following input data:
Algorithm realization
Declare the input array and the resulting array .
#define MAX 1000001 long long a[MAX], res[MAX];
Read the input data.
scanf("%d",&n); for(i = 1; i <= n; i++) scanf("%lld",&a[i]);
Compute the answer for one house, and for two houses.
res[1] = a[1]; if (n > 1) res[2] = max(a[1],a[2]);
Compute the answers for the remaining houses.
for(i = 3; i <= n; i++) res[i] = max(res[i - 2] + a[i], res[i - 1]);
Print the answer.
printf("%lld\n",res[n]);
Java realization
import java.util.*; class Main { static long a[] = new long[1000001]; static long res[] = new long[1000001]; public static void main(String[] args) { Scanner con = new Scanner(System.in); int n = con.nextInt(); for(int i = 1; i <= n; i++) a[i] = con.nextInt(); res[1] = a[1]; if (n > 1) res[2] = Math.max(a[1],a[2]); for(int i = 3; i <= n; i++) res[i] = Math.max(res[i - 2] + a[i], res[i - 1]); System.out.println(res[n]); con.close(); } }
Python realization
Read the input data.
n = int(input()) lst = list(map(int,input().split()))
Initialize the list .
dp = [0] * len(lst)
Compute the answer for one house, and for two houses.
dp[0] = lst[0] if (n > 1): dp[1] = max(lst[0], lst[1])
Compute the answers for the remaining houses.
for i in range(2, len(lst)): dp[i] = max(dp[i-1], dp[i-2] + lst[i])
Print the answer.
print(dp[-1])