#C4939. Maximum Wealth with Constraints
Maximum Wealth with Constraints
Maximum Wealth with Constraints
You are given n houses in a row, where the i-th house has a wealth value wi. You must decide which houses to rob in order to maximize the total wealth. However, there are two restrictions:
- You cannot rob two adjacent houses.
- You can rob at most k houses.
This problem can be formulated using dynamic programming. Let \(\text{DP}[i][j]\) be the maximum wealth that can be robbed from the first \(i\) houses with exactly \(j\) houses robbed. The recurrence relation is:
[ \text{DP}[i][j] = \max\Big(\text{DP}[i-1][j],; w_i + \text{DP}[i-2][j-1]\Big), ]
with the appropriate initialization. Your task is to implement a program that reads from standard input and prints the maximum wealth that can be robbed under these constraints.
inputFormat
The input is given via standard input and consists of two lines:
- The first line contains two integers \(n\) and \(k\) separated by a space, where \(n\) is the number of houses and \(k\) is the maximum number of houses you can rob.
- The second line contains \(n\) space-separated integers representing the wealth values of the houses.
outputFormat
Output a single integer via standard output: the maximum amount of wealth that can be robbed under the given constraints.
## sample6 2
5 1 1 5 10 2
15