LeetCode 121:买卖股票的最佳时间

动态规划可解: 状态方程 + 初始状态,为了更直观的体现状态机,可以把到第 i 天为止的最小价格和到第 i 天能获得的最大收益保存为数组,当然完全可以保存为一个变量的。时间复杂度O(n),空间复杂度O(n)/O(1)

    int maxProfit(vector<int>& prices) {
        const int n = prices.size();
        if (n<=1) return 0;

        vector<int> lowest(n);
        vector<int> porfit(n);
        lowest[0] = prices[0];
        porfit[0] = 0;
        for (int i=1; i<n; i++) {
            if(prices[i] < lowest[i-1])
                lowest[i] = prices[i];
            else
                lowest[i] = lowest[i-1];
            if(prices[i]-lowest[i] < porfit[i-1])
                porfit[i] = porfit[i-1];
            else
                porfit[i] = prices[i] - lowest[i];
        }
        return porfit[n-1];
    }
int maxProfit(vector<int>& prices) {
        const int n = prices.size();
        if (n<=1) return 0;

        int lowest;
        int porfit;
        lowest = prices[0];
        porfit = 0;
        for (int i=1; i<n; i++) {
            if(prices[i] < lowest)
                lowest = prices[i];
            if(prices[i]-lowest > porfit)
                porfit = prices[i] - lowest;
        }
        return porfit;
    }

方法二:

逐项做差得到每日收益数组,将问题转化为连续子数组的最大和问题:

(浙大的数据结构课,剑指Offer,LC的53题都是这道很经典的题目)

debug:第一次因为初始化ans为0,导致输入为[1,2]时结果会出错,重新改了ans初始化值,将与0比较放在最后比一次,即可

    int maxProfit(vector<int>& prices) {
        const int n = prices.size();
        if (n<=1) return 0;

        vector<int> gains(n-1);
        for (int i=0; i<n-1; i++) {
            gains[i] = prices[i+1]-prices[i];
        }

        vector<int> maxProfit(n-1);
        //int ans = 0;
        maxProfit[0] = gains[0];
        int ans = maxProfit[0];
        for(int i=1; i<n-1; i++) {
            maxProfit[i] = max(maxProfit[i-1]+gains[i], gains[i]);
            ans = max(ans, maxProfit[i]);
        }
        return max(ans, 0);
    }
发布了97 篇原创文章 · 获赞 11 · 访问量 2490

猜你喜欢

转载自blog.csdn.net/chengda321/article/details/102671695