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

    Subscribe to see which companies asked this question

    第一次用dp写n^2挂了。超时。后来 看的讨论里面的代码。太弱了
     
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int n=prices.size();
            if(n<=1)return 0;
            int dp1[n]={0};
            int dp2[n]={0};
            int Min=prices[0];
            for(int i=1;i<n;i++){
                dp1[i]=max(dp1[i-1],prices[i]-Min);
                Min=min(Min,prices[i]);
            }
            int Max=prices[n-1];
            for(int i=n-2;i>=0;i--){
                dp2[i]=max(dp2[i+1],Max-prices[i]);
                Max=max(Max,prices[i]);
            }
            int ans=0;
            for(int i=0;i<n;i++){
                ans=max(ans,dp1[i]+dp2[i]);
            }
            return ans;
        }
    };
  • 相关阅读:
    Python基础知识篇
    Django框架
    Django REST Framework框架
    NoSQL
    MySQL恩恩怨怨
    Python奇技淫巧
    一文搞定Flask
    数据结构与算法(Python)
    学习数据分析
    项目杂项
  • 原文地址:https://www.cnblogs.com/pk28/p/5526176.html
Copyright © 2011-2022 走看看