classSolution { public: intmaxProfit(vector<int>& prices){ int n = prices.size() - 1, ans = 0; for (int i = 0; i < n; ++i) ans += max(0, prices[i + 1] - prices[i]); return ans; } };
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmaxProfit(vector<int>& prices){ int cash = 0, hold = -prices[0]; for (int i = 1; i < prices.size(); ++i) { cash = max(cash, hold + prices[i]); hold = max(hold, cash - prices[i]); } return cash; } };