diff --git a/Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp b/Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp new file mode 100644 index 00000000..14c7d2f3 --- /dev/null +++ b/Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp @@ -0,0 +1,29 @@ +/*@author Navneet Jain + * Say you have an array for which the ith element is the price of a given stock on day i. + * If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. + + */ +#include +#include +#include +using namespace std; + +int maxProfit(const vector &A) { + int buy = A[0], flag = 0, i = 1, max_sell = INT_MIN; + int sol = 0; + while(i < A.size()){ + int diff = A[i] - A[i-1]; + //It's a greedy appoach. If current diff is greater than 0, then add that to the solution. + if(diff > 0){ + sol = sol + diff; + } + i++; + } + + return sol; +} + +int main(){ + vector A = {1,2}; + cout << maxProfit(A); +} diff --git a/Dynamic Programming/buy_sell_stocks/README.md b/Dynamic Programming/buy_sell_stocks/README.md new file mode 100644 index 00000000..75291b0d --- /dev/null +++ b/Dynamic Programming/buy_sell_stocks/README.md @@ -0,0 +1,14 @@ +Problem Statement: +Say you have an array for which the ith element is the price of a given stock on day i. +If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. + +Solution Approach: +If you buy your stock on day i, you’d obviously want to sell it on the day its price is maximum after that day. +So essentially at every index i, you need to find the maximum in the array in the suffix. +Now this part can be done in 2 ways : +1) Have another array which stores that information. +max[i] = max(max[i+1], A[i]) + +2) Start processing entries from the end maintaining a maximum till now. Constant additional space requirement. + +