zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock III

    题目:

    ay 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;
        }
    };
  • 相关阅读:
    javascript解决方案插件
    vscode前端快速开发插件
    html5新增语义标签
    vscode快捷键大全
    vscode/sublime前端开发快捷键
    vscode自动缩进快捷键
    Android平台OpenGL ES/Assimp/OpenCV/GLM集成说明
    将AOSP源码导入到Android Studio进行查看
    Android OTA升级
    Android构建系统
  • 原文地址:https://www.cnblogs.com/raichen/p/4933017.html
Copyright © 2011-2022 走看看