Stock Buy and Sell Problem
In this class, We discuss Stock Buy and Sell Problem.
The reader can take a full competitive coding course. Click Here.
Problem:
Given, The cost of stock each day in an array.
Find the segment of days in which you buy and sell the stock so that your profit is maximum between those days.
Example:
N = 7
A = [100, 180, 260, 310, 40, 535, 695]
Output: (0,3) (4,6)
On the first day, the share cost is 100, and on the fourth day, the cost is 310.
Buy on the first day and sell on the fourth day, we get a profit of 210.
Similarly, buy on the fifth day and sell on the seventh day.
We get a profit of 655.
Total profit = 210 + 655 = 865
The output contains a list of array indexes.
Condition: Sell the stock before you buy new stock
Example 2:
[4,2,2,2,2]
Output: No profit
logic:
Explanation of logic provided in the video.
Code:
class Solution:
def stockBuySell(self, price, n):
lis=[]
if (n == 1):
return
i = 0
while (i < (n – 1)):
while ((i < (n – 1)) and (price[i + 1] <= price[i])):
i += 1
if (i == n – 1):
break
buy = i
i += 1
while ((i < n) and (price[i] >= price[i – 1])):
i += 1
sell = i – 1
lis.append([buy,sell])
return li
maximum = 0
print(“enter n value”)
n = int(input())
print(“enter n days stock prices”)
price=list(map(int,input().strip().split()))
ob = Solution()
j = ob.stockBuySell(price,n)
if not j:
print(“No Profit”)
else:
for i in j:
x = price[i[1]]-price[i[0]]
maximum=maximum+x
print(maximum)