• [LeetCode] 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).

    Solution:

    class Solution {
    public:
        
    int maxProfit(vector<int> &prices) {
            if(prices.size() < 2) return 0;
            int ans = 0;
            int day_num = prices.size();
            int *postMax = new int[day_num + 1], *postBest = new int[day_num + 1];//the max start from i, buy on the day i, the max profit
            postMax[day_num - 1] = 0;
            postBest[day_num - 1] = 0;
            for(int i = day_num - 2;i >= 0; i--)
            {
                postMax[i] = max(postMax[i + 1], prices[i + 1]);
                postBest[i] = max(postBest[i + 1], postMax[i] - prices[i]);
            }
            /*
            cout << "max: ";
            for(int i = 0;i < day_num;i++)
                cout << curMax[i] << " ";
            cout << endl;
            cout << "Best: ";
            for(int i = 0;i < day_num;i++)
                cout << curBest[i] << " ";
            cout << endl;
            */
            //two transactions, once the first sell out at day j, the next best choo        
            //sell on the day i, the best time to buy
            ans = postBest[0];
            int *preBest = new int[day_num + 1], *preMin = new int[day_num + 1];//the max profit of the first transaction.
            preBest[0] = 0;
            preMin[0] = prices[0];
            int tmpProfit = 0;
            for(int i = 1;i < day_num - 2;i++)
            {
                preBest[i] = max(preBest[i - 1], prices[i] - preMin[i - 1]);
                preMin[i] = min(preMin[i - 1], prices[i]);
                tmpProfit = preBest[i] + postBest[i + 1];
                //cout << "temp = " << tmpProfit << endl;
                if(tmpProfit > ans) ans = tmpProfit;
            }
    
            return ans;
        }
    };
    View Code
  • 相关阅读:
    element 步骤条steps 点击事件
    element-ui的rules中正则表达式
    从master分支创建自己的分支
    2.1 系统调用io实现原理
    2-3形参和实参
    2-2函数
    2-1.编译和链接
    linux高编信号-------setitimer()、getitimer()
    linux高编IO-------有限状态机编程原理(mycpy)
    linux高编线程-------线程同步-条件变量
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3840438.html
Copyright © 2020-2023  润新知