Why my C++ code is not accepted


  • 0
    F

    while I submit my code as follow, the feed back shows that mine is wrong at the test case[2,1]. But once I run the test case [2,1] separately, it gives the right answer. I just don't know why it happened.

      class Solution {
        public:
            int maxProfit(vector<int>& prices) {
                int buy=0;//0 for not hold 1 for hold
                int money=0;// profit
                for(int i=0;i<prices.size();i++){
                    if((prices[i]<prices[i+1])&&(buy==0)){
                        money-=prices[i];
                        buy++;
                    }
                    if((prices[i]>prices[i+1])&&buy){
                        money+=prices[i];
                        buy--;
                    }
                }
                return money;
                
            }
        };

  • 0
    Z

    Because in your loop, prices[i+1] accesses the i+1 element which exceeds the length of the prices, it'll caused unknown result when you run.


Log in to reply
 

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