This is a C++ Program that Solves Stolen Values Problem using Dynamic Programming technique.
There are n houses built in a line, each of which contain some value in it. A thief is going to steal in these houses. But he cannot steal in two adjacent houses. What is maximum value he can steal?
Maximum stolen value from first i houses of the line can be either the maximum stolen value from first i-1 houses of the line or maximum stolen value from i-2 houses of the line plus value in ith house. So, we will choose maximum of these. We will calculate the values in bottom up manner.
number of houses=7 values=9, 3, 5, 8, 2, 4, 7 maximum stolen value=24 by stealing from first, fourth and seventh house
Here is source code of the C++ Program to Solve Stolen Values Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int maxStolen(int n, int values)
//array to store results
//dp[i]=maximum stolen value from first i houses
//maximum stolen value from first i houses of the line can be
//either the maximum stolen value from first i-1 houses of the line
//or maximum stolen value from i-2 houses of the line plus value in ith house
//so, we will choose maximum of these
cout<<"Enter the number of houses"<<endl;
cout<<"Enter the values in the houses"<<endl;
cout<<"Maximum stolen value is "<<endl;
In the main function, we ask the user to input the value of number of houses and values in each house to be stolen. We pass these values to the function maxStolen as parameters. This function will calculate the expected result and return it. The returned value will be displayed.
Case-1: $ g++ stolen_values.cpp $ ./a.out Enter the number of houses 7 Enter the values in the houses 9 3 5 8 2 4 7 Maximum stolen value is 24
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.