For input [2,1,2,0,1] output shouldn't be 2 instead of 1 ?

• class Solution {

public:

``````int maxProfit(vector<int>& prices) {
int tobuy=1,profit=0;
for(int i=0;i<prices.size();i++){
if(tobuy && i!=prices.size()-1 && prices[i]<=prices[i+1]){
if(i==0 || prices[i]<=prices[i-1]){
profit-=prices[i];
tobuy=0;
}
}
else if(tobuy==0 && i!=0 && prices[i]>=prices[i-1]){
if(i==prices.size()-1 || prices[i]>=prices[i+1]){
profit+=prices[i];
tobuy=1;
}
}
}
return profit;
}
``````

};

• No, it must be 1, you must buy the stock first and then sell it instead of sell and buy.

• I too had same doubt for input [2,1,2,0,1] output shouldn't be 2?
buy on day 2 sell on day 3 -> Profit=1
then buy on day 4 and sell on day 5 ->profit=1
Total profit =2.

what is wrong in it? We are doing only 1/none transaction on a day.

• Because in this question, we are only permitted to complete at most one transaction overall (not on a day).

• Got it, Thank you.

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