Maximum Profit Stock Prices Algorithm

By   Tewodros   Date Posted: Oct. 1, 2021  Hits: 961   Category:  Algorithm   Total Comment: 2             A+ A-


side

Given a list of numbers that represent the values of stocks that you can buy or sell at a given day, we would like to find maximum profit that we get by buying a stock at the minimum price and selling it at the maximum price. You must buy first before you sell a stock and you can buy and sell only one time. 

Example:

A = { 8, 3, 2, 6, 7, 2, 7, 8 };  Ans = 6. You can buy at a minimum price of 2 and sell it at a maximum price of 8

Solution:

Here, we will go through the numbers in the list and try to see where we can buy at a minimum price. We can assume the first element is the minimum but update it if we find less number than this.

Also we will start with maxprofit =0 and we will see if we can get a better profit by checking each element minus minimum is greater than our maxproft, if it does we will update our max profit.

The trick here is we should always do finding the minimum part first before we attempt to do max profit calculation since it depends on it.

 

           if (prices.Length <= 0) 

              return 0;

           int minBuyPrice = prices[0];

           int maxProfit = 0;

 

           for (int i = 1; i < prices.Length; i++)  {

               if (prices[i] <= minBuyPrice)  {

                   minBuyPrice = prices[i];

               }

               else   {

                   if (prices[i] - minBuyPrice > maxProfit)

                       maxProfit = prices[i] - minBuyPrice;

               }

           }

           return maxProfit;


Tags



Back to Top



Related Blogs


Previous Comments: 2

Posted By:  Tewodros
Tuesday, October 19, 2021
ted
Posted By:  Tewodros
Tuesday, October 19, 2021

ted ted




Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* vldslf

Back to Top