From 6bceb9ce2835942c6f7dfcaa420ea18d5c9935a6 Mon Sep 17 00:00:00 2001 From: Navneet Jain Date: Wed, 31 Oct 2018 10:23:49 +0530 Subject: [PATCH] added code for best time to buy sell stock (#136) --- .../buy_sell_stocks/C++/buy_sell_stock_dp.cpp | 29 +++++++++++++++++++ Dynamic Programming/buy_sell_stocks/README.md | 14 +++++++++ 2 files changed, 43 insertions(+) create mode 100644 Dynamic Programming/buy_sell_stocks/C++/buy_sell_stock_dp.cpp create mode 100644 Dynamic Programming/buy_sell_stocks/README.md 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. + +