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. 买卖股票的最佳时机,计算收益时减去手续费)

  

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

posted @ 2021-04-18 06:39  Johnny、  阅读(59)  评论(0编辑  收藏  举报