0

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;
  • At the time your code encounters the 10, the current minima is 3 for a profit of 7. When it encounters the 9 the current minima is 1 for a profit of 8 which is better. You need to rethink your approach as there is currently no relationship between buying and selling, let alone short selling. – Botje Nov 03 '20 at 09:58
  • You can't determine the maximum profit until you know both the highest and the lowest price. Shorting is a gamble. – molbdnilo Nov 03 '20 at 10:13

1 Answers1

1

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

Serial Lazer
  • 1,667
  • 1
  • 7
  • 15