Search code examples
c++arrayslogicstockmaximum-profit-problem

How to achieve shortsell condition in this stock profit maximisation code?


This is the code I have written to buy the stock when the price is lowest and sell when it is max. I want to implement shortsell condition here like I want to sell even before buying. Consider this array of stock prices for a week.

3 10 4 1 9 3 2

Now I want to sell when the price is 10 and buy when the price is 1 to achieve profit of 9.

But my code buys when the price is 1 and sell it on 9. I can achieve max profit by searching for max number and min no. but would like to implement via the logic below and want to know what condition below is not allowing me for shortsell.

    long  profit=a[1]-a[0];
    long  minima=a[0];
    for(long  i=1; i<noOfDays; i++)
    {
        if(a[i]-minima>profit)
        {
            profit=a[i]-minima;
        }
        
        if(a[i]<minima)
        {
            minima=a[i];
        }
    }
    cout<<profit;

Solution

  • If you allow shortselling, your profit is always = max(array) - min(array) without exceptions.