From d64c7aad7b557a8b443ae406cddfb2200c1b1355 Mon Sep 17 00:00:00 2001 From: soumik2012 <66599363+soumik2012@users.noreply.github.com> Date: Wed, 21 Oct 2020 20:27:51 +0530 Subject: [PATCH] Added Maximum-Profit-by-buying-and-selling-stocks --- ...um Profit by buying and selling stocks.txt | 13 +++++++ .../solution.py | 35 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 Basic Math/Maximum-Profit-by-buying-and-selling-stocks/Maximum Profit by buying and selling stocks.txt create mode 100644 Basic Math/Maximum-Profit-by-buying-and-selling-stocks/solution.py diff --git a/Basic Math/Maximum-Profit-by-buying-and-selling-stocks/Maximum Profit by buying and selling stocks.txt b/Basic Math/Maximum-Profit-by-buying-and-selling-stocks/Maximum Profit by buying and selling stocks.txt new file mode 100644 index 0000000..0d73070 --- /dev/null +++ b/Basic Math/Maximum-Profit-by-buying-and-selling-stocks/Maximum Profit by buying and selling stocks.txt @@ -0,0 +1,13 @@ +Problem Statement: Suppose you have given the stock prices for respective days like (100, 180, 260, 310, 40, 535, 695). The stock price for the 1st day is 100, 2nd day it is 180 and so on. Write a Python program to determine what days the user should bye and sell the stocks to get the maximum profit. + +In the above case, in the following scenarios user will get maximum profit. + +Buy stock on 1st day (100) +Sell stock on 4th day (310) +Buy stock on 5th day (100) +Sell stock on 7th day (695) +Algorithm steps: + +Find the local minima (buying stock) +Find local maxima (selling stock) +Repeat until all days are covered. \ No newline at end of file diff --git a/Basic Math/Maximum-Profit-by-buying-and-selling-stocks/solution.py b/Basic Math/Maximum-Profit-by-buying-and-selling-stocks/solution.py new file mode 100644 index 0000000..aaf8926 --- /dev/null +++ b/Basic Math/Maximum-Profit-by-buying-and-selling-stocks/solution.py @@ -0,0 +1,35 @@ +liStocks = [100, 180, 260, 310, 40, 535, 695] + +#find local minima +def findMin(liStocks): + for i, val in enumerate(liStocks[:-1]): + if val < liStocks[i+1]: + return i, val + return -1, -1 + +#find local maxima +def findMax(liStocks): + for i, val in enumerate(liStocks[:-1]): + if val > liStocks[i+1]: + return i, val + return i+1, liStocks[-1] + + + +def byeSellStock(): + index=0 + while index < len(liStocks): + i, val = findMin(liStocks[index:]) + if i > -1: + index=i+index + print("bye stock on day ", index+1, val) + else: + break + + i, val = findMax(liStocks[index:]) + index=i+index + print("sell stock on day ", index+1, val) + + +if __name__ == "__main__": + byeSellStock() \ No newline at end of file