# Why does the position of edge case statement matter so much?

• class Solution {
public:
int maxProfit (vector<int> &prices) {

``````	if (prices.size() ==0)	 return 0;
int min = prices[0];
int maxP = 0;
for (int i = 1; i < prices.size(); i++)
{
if (prices[i] - min>maxP)
maxP = prices[i] - min;
if (prices[i] < min)
min = prices[i];
}
return maxP;
}
``````

};

The line if (prices.size() ==0) return 0; is to judge for the edge case. But if I put this line in the middle of the function (for example, put this line below int maxP = 0; ), it will show Runtime error:Last executed input: []
Why does the position of edge case statement matter so much? Why can't I put the edge case judge statement in the middle of the function?

• int min = prices[0]; is accessing the first element of prices vector, if (prices.size() ==0) return 0; is not called before above statement, then prices[0] is accessed which leads to run time error as prices vector is indeed empty for the case when input: []

• Thanks so much!

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