Perfect on my Mac, wrong result here.


  • 0
    Z

    test case [1, 2]
    the correct result is 1. My code shows 1 on my local computer as well.
    But Leetcode told me that my code gives a wrong result, 18.

    Here is the code, it works perfectly fine on my local computer. Can anyone help me to look at it? Since it is not a run time error. I suppose it is not from compiler difference... Thank you very much!

    int maxProfit(vector<int> &prices) {
        if(prices.size()<=1) return 0;
        int result=0;
        std::vector<int> forwardGap(prices.size());
        // processing forward gaps, just like bestTimeToBuySell I
        // this part collects the max profit in forward order, and update the result
        int myMin=prices[0]; int gap=0;
        for(int ii=0;ii<prices.size();++ii){
            if(prices[ii]-myMin>gap)
                gap=prices[ii]-myMin;
            forwardGap[ii]=gap;
            if(prices[ii]<myMin)
                myMin=prices[ii];
        }
        //Collect max profit in backward order. Every time we add it with the
       // forward max profit of ii-1
        int myMax=prices[prices.size()-1];
        gap=0;
        for(int ii=prices.size()-1;ii>=0;--ii){
            if(myMax-prices[ii]>gap)
                gap=myMax-prices[ii];
            // update the result
            result=result>(gap+forwardGap[ii-1])?result:(gap+forwardGap[ii-1]);
            if(prices[ii]>myMax)
                myMax=prices[ii];
        }
        return result;
    }

  • 0
    Z

    Hi guys,

    I figured out the problem. There is one concept need to be mentioned.

    You can purchase and sell the stock on the same day. You can buy it back right after you sold it.

    In my code, I tried to access forwardGap[-1];

    So if I change my code to be like

    // update the result
        result=result>(gap+forwardGap[ii])?result:(gap+forwardGap[ii]);
    

    It is accepted. Honestly I don't know why I can get correct result on my local computer...


Log in to reply
 

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