Leetcode解题笔记121. Best Time to Buy and Sell Stock [Easy] 动态规划

版权声明:自由转载-非商用-非衍生-保持署名 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;
    }
};

猜你喜欢

转载自blog.csdn.net/mgsweet/article/details/78747054
今日推荐