# O(n) time O(1) space -- very elegant solution with comments

• ``````class Solution {
public:
int maxProfit(vector<int>& prices) {
vector<int> res(4, 0);
res[0] = INT_MIN;
res[2] = INT_MIN;
for(int i = 0; i < prices.size(); ++i) {
res[3] = max(res[3], res[2] + prices[i]);  // Transaction 2: sell
res[2] = max(res[2], res[1] - prices[i]);  // Transaction 2: buy
res[1] = max(res[1], res[0] + prices[i]);  // Transaction 1: sell
res[0] = max(res[0], -prices[i]);          // Transaction 1: buy
}
return max(res[1], res[3]);
}
};``````

• res[3] actually covers res[1] , so just need to return res[3]

• Yes, you are right!

• what is the real meaning for res[3] ?

• Could you help explain why res[3] covers res[1]?

• I think it's elegant and good indeed, however, i don't understand how does it work. Could anyone explain it for me??

• I think it's elegant and good indeed, however, i don't understand how does it work. Could anyone explain it for me??

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