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;
        }
    };

  • 相关阅读:
    队列的顺序存储实现
    栈的顺序存储实现2
    企业版循环单链表
    STL-list
    EXCEL多条件查询之VLOOKUP+IF{1,0} 踩坑
    MybatisPlus Wrapper方法
    sequence:创建、使用
    Java中List集合去除重复数据的方法
    windows下安装nginx和常用命令
    MySQL8.0.20下载并安装
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4128114.html
Copyright © 2011-2022 走看看