Why do I have to add "if(prices.size() == 0) return 0;"?


  • 0
    X

    if I submit like this:

    int maxProfit(vector<int> &prices) {
        int answer = 0;
    	for(int i = 0;i < prices.size()-1;i++)
    	{
    		if(prices[i+1]>prices[i])
    			answer += prices[i+1]-prices[i];
    	}
    	return answer;
    }
    

    It gives me a "Run Error"
    If I add a "if(prices.size() == 0) return 0;"before the for loop, then it is accepted. If the vector is empty, then it shouldn't enter the for loop, so why do I have to add the judge?


  • 0
    C

    price.size() is unsigned, so -1 is not unsigned.
    change that like this: (int)(prices.size() - 1)


Log in to reply
 

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