zoukankan      html  css  js  c++  java
  • leetcode_买卖股票_暴力递归

    ------------恢复内容开始------------

    #include <iostream>
    #include <algorithm>
    #include <vector>
    using namespace std;
    
    // 122. 买卖股票的最佳时机 II---199/200 个通过测试用例
    // 可无数次交易
    class Solution {
    public:
        int profit(vector<int>& prices, vector<int>& dp, int start)
        {
            int n=prices.size();
            if(start>=n) return 0;
            if(dp[start]) return dp[start];
            int curMin = prices[start], res=0;
            for(int i=start+1; i<n; ++i)
            {
                curMin = min(curMin, prices[i]);
                res = max(res, prices[i]-curMin+profit(prices, dp, i+1));
            }
            dp[start]=res;
            return res;
        }
        int maxProfit(vector<int>& prices) {
            int n=prices.size();
            vector<int> dp(n);
            return profit(prices, dp, 0);
        }
    };
    
    
    // 123. 买卖股票的最佳时机 III---202/214 个通过测试用例
    // 可2次交易(代码同 188. 买卖股票的最佳时机 IV, 令k=2)
    
    
    // 188. 买卖股票的最佳时机 IV---通过
    // 执行用时:1280 ms, 在所有 C++ 提交中击败了5.50%的用户
    // 内存消耗:11.6 MB, 在所有 C++ 提交中击败了47.99%的用户
    // 可k次交易
    class Solution {
    public:
        int profit(vector<int>& prices, vector<vector<int>>& dp, int start, int k)
        {
            int n=prices.size();
            if(start>=n || k==0) return 0;
            if(dp[start][k]) return dp[start][k];
            int curMin = prices[start], res=0;
            for(int i=start+1; i<n; ++i)
            {
                curMin = min(curMin, prices[i]);
                res = max(res, prices[i]-curMin+profit(prices, dp, i+1, k-1));
            }
            dp[start][k]=res;
            return res;
        }
        int maxProfit(int k, vector<int>& prices) {
            int n=prices.size();
            vector<vector<int>> dp(n, vector<int>(k+1));
            return profit(prices, dp, 0, k);
        }
    };
    
    
    // 309. 最佳买卖股票时机含冷冻期---通过
    // 执行用时:152 ms, 在所有 C++ 提交中击败了12.22%的用户
    // 内存消耗:11.1 MB, 在所有 C++ 提交中击败了54.00%的用户
    // 可无数次交易 有一天冷冻期 (代码同122. 买卖股票的最佳时机 II i+1改成i+2隔天交易)
    
    
    // 714. 买卖股票的最佳时机含手续费---34/44 个通过测试用例
    // 可无数次交易(代码同122. 买卖股票的最佳时机,计算收益时减去手续费)
    

      

    ------------恢复内容结束------------

  • 相关阅读:
    MVC CONTROLS TOOLKIT
    activemq Example
    OWASP
    ActiveMQ持久化消息的三种方式
    sqlyog
    dotnet压缩
    asp.net ajax 环境 c#与js互调
    asp.net 初步入门使用正则抓取网页信息
    用ASP.NET with C# 绘制曲线图(Curve图)转
    asp.net 中使用excel组件权限设置
  • 原文地址:https://www.cnblogs.com/exciting/p/14672770.html
Copyright © 2011-2022 走看看