zoukankan      html  css  js  c++  java
  • 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).

    最多只能购买两次,那么以i为划分,计算以i结尾的左边子数组的最大交易,和以i开头的右边子数组的最大交易。

    问题转换为求两个子数组的最大利益,这个就是Best Time to Buy and Sell Stock I,总的时间复杂度是O(n^2);

    再做优化,先从左到右计算以i结尾的最大利益,这个可以在o(n)的时间内完成,

    然后从末尾开始往前遍历,计算从[n,i]的最大利益。

    那么最大利益就是在i这个划分上的左边的最大+右边的最大。

    其实这个题和还有一个题很相似,就是,以A[1..n]数组构造B[1..n],使得B[i]=A[1]*A[2]*...*A[i-1]*A[i+1]*...A[n];

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int pricesSize = prices.size();
            if(pricesSize<=1){
                return 0;
            }
            int lowPrice = prices[0];
            vector<int> maxProfits(pricesSize,0);
            for(int i=1;i<pricesSize;i++){
                maxProfits[i] = max(prices[i] - lowPrice,maxProfits[i-1]);
                lowPrice = min(lowPrice,prices[i]);
            }
            int maxProfit = maxProfits[pricesSize-1],rightMaxProfit=0;
            int highPrice = prices[pricesSize-1];
            for(int i=pricesSize-2;i>=0;i--){
                rightMaxProfit = max(highPrice - prices[i],rightMaxProfit);
                maxProfit = max(maxProfit,max(maxProfits[i]+rightMaxProfit,maxProfits[i]));
                highPrice = max(highPrice,prices[i]);
            }
            return maxProfit;
        }
    };
  • 相关阅读:
    40. 组合总和 II(回溯法)
    39. 组合总和(回溯法)
    1640. 能否连接形成数组
    890. 查找和替换模式
    386. 字典序排数
    20. 有效的括号
    496. 下一个更大元素 I
    115. 不同的子序列
    59. 螺旋矩阵 II
    HTML基本结构,标签
  • 原文地址:https://www.cnblogs.com/zengzy/p/5004785.html
Copyright © 2011-2022 走看看