Max Stock Profit where multiple buy and sell allowed Algo

By   Tewodros   Date Posted: Oct. 16, 2021  Hits: 812   Category:  Algorithm   Total Comment: 0             A+ A-


side

 

Given a list of integers representing the values of stocks on a daily basis, we would like to calculate  Max Stock Profit where multiple buy and sell allowed. In other words you can sell a stock after you purchased it at any given day and able to purchase again and sell it repeatedly. In the end, you profit should be the sum of the individual profits you have accumulated over and over again. 

Example:

{7, 1, 5, 3, 6, 4 }  Max Profit = 7 

Since you can buy on day 2 at price 1 and sell on day 3 at price 5 with a profit of 5-1 = 4 ;  

In addition, you may buy on day 4 at price 3 and sell on day 5 at price 6 with a profit of 6 - 3 = 3

Therefore, Max Profit =  4+3 = 7

Example:

{ 8, 3, 2, 6, 7, 2, 7, 8 }; Max Profit = 11 

Since you can buy at 2 and sell at 6 ;  buy at 2 and sell at 8 ==>  Max Profit =  5+6 =11

Solution:

The trick here is you can sell and buy the same stock at the same price on the same day. 

This problem can be solved easily if we can understand that this is really all about calculating the cumulative sum of the difference between a(i) and a(i-1) if a(i) > a(i-1).

For example for the first array, we can see that the only time we increment cumulative sum is at  5-1  +    6-3  = 4 + 3 = 7

For the second array, we do it at 6-2  +  7-6  +  7-2  + 8-7   = 4 + 1 + 5 + 1 = 11

 

  public static int solution(int[] prices)  {

           int ans = 0;

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

               if (prices[i] > prices[i - 1])

                   ans += prices[i] - prices[i - 1];

           }

           return ans;

       }

 


Tags



Back to Top



Related Blogs






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

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


Security Code:* gajjne

Back to Top