This is a C++ Program that Solves the Stock Market Problem using Dynamic Programming technique.
Given the price of share on n days, find the maximum profit that you can make by buying and selling a share at most twice.
In this problem, we are required to find the maximum obtainablem profit with the constraint of buying and selling at most twice. First, we will find the required values with the constraint of 1. Then, using these values we can easily find the results for the constaint of two.
price=8, 10, 5, 30, 25, 35 Maximum profit that could be made by buying and selling a share at most twice=35 (by buying on third day and selling on fourth day and then buying on fifth day and selling on sixth day
Here is source code of the C++ Program to Solve the Stock Market Problem. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
using namespace std;
int maxProfit(int n, vector<int> &a)
//dp[i]=maximum profit by buying and selling a stock just once a day by using only values a[0...i]
//dp[i]=maximum profit by buying and selling a stock just once a day by using only values a[i...n-1]
//i is the value at which stock will be sold
//i is the value at which stock will be purchased
cout<<"Enter the number of stock values ";
cout<<"Enter the values of stock on each day "<<endl;
cout<<"Maximum profit that could be made by buying and selling a share at most twice"<<endl;
The main function takes input for the stock values. Then, these values are passed to the function maxProfit as parameters. In the maxProfit function, we created a matrix to memoize values. The final result is returned by this function which is displayed by the standard output.
Case-1: $ g++ stock_profit.cpp $ ./a.out Enter the number of stock values 6 Enter the values of stock on each day 8 10 5 30 25 35 Maximum profit that could be made by buying and selling a share at most twice 35
Sanfoundry Global Education & Learning Series – Dynamic Programming Problems.
To practice all Dynamic Programming Problems, here is complete set of 100+ Problems and Solutions.