Open In App

Python Program For Stock Buy Sell To Maximize Profit

Last Updated : 17 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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. For example, if the given array is {100, 180, 260, 310, 40, 535, 695}, the maximum profit can earned by buying on day 0, selling on day 3. Again buy on day 4 and sell on day 6. If the given array of prices is sorted in decreasing order, then profit cannot be earned at all.

Naive approach: A simple approach is to try buying the stocks and selling them on every single day when profitable and keep updating the maximum profit so far.

Below is the implementation of the above approach:

Python3




# Python3 implementation of the approach
  
# Function to return the maximum profit
# that can be made after buying and
# selling the given stocks
def maxProfit(price, start, end):
  
    # If the stocks can't be bought
    if (end <= start):
        return 0;
  
    # Initialise the profit
    profit = 0;
  
    # The day at which the stock
    # must be bought
    for i in range(start, end, 1):
  
        # The day at which the
        # stock must be sold
        for j in range(i+1, end+1):
  
            # If buying the stock at ith day and
            # selling it at jth day is profitable
            if (price[j] > price[i]):
                  
                # Update the current profit
                curr_profit = price[j] - price[i] + maxProfit(price, start, i - 1)+ maxProfit(price,  j + 1, end);
  
                # Update the maximum profit so far
                profit = max(profit, curr_profit);
  
    return profit;
  
# Driver code
if __name__ == '__main__':
    price = [100, 180, 260
             310, 40, 535, 695];
    n = len(price);
    print(maxProfit(price, 0, n - 1));
# This code is contributed by Rajput-Ji


Output

865

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient approach: If we are allowed to buy and sell only once, then we can use following algorithm. Maximum difference between two elements. Here we are allowed to buy and sell multiple times. 
Following is the algorithm for this problem.  

  1. Find the local minima and store it as starting index. If not exists, return.
  2. Find the local maxima. and store it as an ending index. If we reach the end, set the end as the ending index.
  3. Update the solution (Increment count of buy-sell pairs)
  4. Repeat the above steps if the end is not reached.

Python3




# Python3 Program to find 
# best buying and selling days
  
# This function finds the buy sell
# schedule for maximum profit
def stockBuySell(price, n):
      
    # Prices must be given for at 
    # least two days
    if (n == 1):
        return
      
    # Traverse through given price array
    i = 0
    while (i < (n - 1)):
          
        # Find Local Minima
        # Note that the limit is (n-2) as 
        # we are comparing present element 
        # to the next element
        while ((i < (n - 1)) and 
                (price[i + 1] <= price[i])):
            i += 1
          
        # If we reached the end, break
        # as no further solution possible
        if (i == n - 1):
            break
          
        # Store the index of minima
        buy = i
        i += 1
          
        # Find Local Maxima
        # Note that the limit is (n-1) as we are
        # comparing to previous element
        while ((i < n) and 
               (price[i] >= price[i - 1])):
            i += 1
              
        # Store the index of maxima
        sell = i - 1
          
        print("Buy on day: ",buy,"    ",
                "Sell on day: ",sell)
          
# Driver code
  
# Stock prices on consecutive days
price = [100, 180, 260
         310, 40, 535, 695]
n = len(price)
  
# Function call
stockBuySell(price, n)
# This is code contributed by SHUBHAMSINGH10


Output

Buy on day:  0      Sell on day:  3
Buy on day:  4      Sell on day:  6

Time Complexity: The outer loop runs till I become n-1. The inner two loops increment value of I in every iteration. So overall time complexity is O(n)
Auxiliary Space : O(1) since using constant variables

Valley Peak Approach:

In this approach, we just need to find the next greater element and subtract it from the current element so that the difference keeps increasing until we reach a minimum. If the sequence is a decreasing sequence so the maximum profit possible is 0.

Python3




# Python3 program for the 
# above approach
def max_profit(prices: list
               days: int) -> int:
    profit = 0
  
    for i in range(1, days):
  
        # Checks if elements are adjacent 
        # and in increasing order
        if prices[i] > prices[i-1]:
  
            # Difference added to 'profit'
            profit += prices[i] - prices[i-1]
  
    return profit
  
# Driver Code
if __name__ == '__main__':
  
    # Stock prices on consecutive days
    prices = [100, 180, 260
              310, 40, 535, 695]
  
    # Function call
    profit = max_profit(prices, len(prices))
    print(profit)
  
 # This code is contributed by vishvofficial.


Output

865

Time Complexity: O(n)
Auxiliary Space: O(1)

Please refer complete article on Stock Buy Sell to Maximize Profit for more details!



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads