Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.
dp[i]
表示第 i + 1
天卖出可获得的最大利润,如果最大利润为负,则无买入卖出class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) {
return 0;
}
vector<int> dp(prices.size());
int res = 0;
for (int i = 1; i < dp.size(); ++i) {
dp[i] = max(dp[i - 1] + prices[i] - prices[i - 1], 0);
res = max(res, dp[i]);
}
return res;
}
};