Simple C Solution -> 7ms


  • 0
    A

    int maxProfit(int prices[], int n){
    int maxDiff = 0,buy = 0, sell = 0;
    int min = prices[0];

    for(int i=1;i<n;i++)
    {
        if(min > prices[i])
            min = prices[i];
        else
        {
            if(prices[i] - min > maxDiff)
            {
                sell = i;
                maxDiff = prices[i] - min;
                buy = min;
            }
            else if((prices[i]-prices[buy] > maxDiff))
            {
                 sell = i;
                maxDiff = prices[i]-prices[buy];
                
            }
        }
    }
    
    return maxDiff;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.