版权声明:自由转载-非商用-非衍生-保持署名 https://blog.csdn.net/mgsweet/article/details/78747054
解题思路
设v[i]为第i天前的购入最便宜值,则v[i] = min(v[i - 1], prices[i - 1]), 取一变量记录最大的prices[i] - v[i]即可。
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.empty()) return 0;
int maxW = 0;
vector<int> v(prices.size());
v[0] = prices[0];
for (int i = 1; i < prices.size(); i++) {
v[i] = min(v[i - 1], prices[i - 1]);
maxW = max(prices[i] - v[i], maxW);
}
return maxW;
}
};