Best time to buy and Sell stock in Python

Best time to buy and Sell stock in Python

On this page, we will learn to create a Program to find Best time to buy and Sell stock in Python programing language.

Example:

  • Input: [70, 150, 230, 280, 10, 505, 665]
  • Output: We can make a maximum profit of 655 
  • Explanation: For the given set of stock prices we can make a maximum profit of 655 by buying the stock on day 4 & selling it on day 6
Best time to buy and sell stock in Python

Problem Statement

 The cost of a stock on each day is given in an array, find the max profit that you can make by buying and selling in those days.

Rules

  1. We are allowed to buy and sell only once
  2. We can not sell before buying the stock

 If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

 For example, if the given array is [70, 150, 230, 280, 10, 505, 665], the maximum profit of 655 can be earned by buying on day 4, selling on day 6.

Algorithm

  • Initialize a variable to store profit (pro)
  • Iterate using a for loop between 0 to one less then length of input array
  • Run a nested for loop from range i+1 to length of array
  • If arr[j] – arr[i] is greater then pro then change the value of pro to arr[j] – arr[i]
  • After the loop ends pro stores the required answer

Python Code

Run
def profit(arr):
    pro = 0
    for i in range(len(arr) - 1):
        for j in range(i + 1, len(arr)):
            if arr[j] - arr[i] > pro:
                pro = arr[j] - arr[i]
    return pro


array = [70, 150, 230, 280, 10, 505, 665]
print("We can make maximum profit of", profit(array))

Output

We can make maximum profit of 655

For similar question click on given button.