zoukankan      html  css  js  c++  java
  • 【LeetCode】123. Best Time to Buy and Sell Stock III

    Best Time to Buy and Sell Stock III

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete at most two transactions.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    动态规划

    使用两个数组,forw和back。

    forw[i]表示从0到i的最优买卖值(低买高卖,为正)。需要一次从左往右遍历。

    back[i]表示从m-1到i的最差买卖值(高买低卖,为负)。需要一次从右往左遍历。

    再对应元素相减:forw[i]-back[i]的最大值即解。

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int m = prices.size();
            if(m == 0)
                return 0;
            
            int ret = 0;
            vector<int> forw(m, 0);
            vector<int> back(m, 0);
            
            //forward
            int curMin = prices[0];
            for(int i = 1; i < m; i  ++)
            {
                curMin = min(curMin, prices[i]);
                forw[i] = max(forw[i-1], prices[i]-curMin);
            }
            //backward
            int curMax = prices[m-1];
            for(int i = m-2; i >= 0; i --)
            {
                curMax = max(curMax, prices[i]);
                back[i] = min(back[i+1], prices[i]-curMax);
                
                ret = max(ret, forw[i]-back[i]);
            }
            
            return ret;
        }
    };

  • 相关阅读:
    Harbor安装 -- 企业级Registry仓库
    https原理
    第十节
    第九节
    第八节
    Spring中用到的部分设计模式
    代理模式及实现
    单例模式的实现
    索引
    第九章 集合
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4128114.html
Copyright © 2011-2022 走看看