leetcode Best Time to Buy and Sell Stock 系列

121. Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.

way-1:动态规划,遇到临时最小的,就保存(1),计算后面比它大的差,保留最大(6-1),遇到后面如果有更小的(0),就保存(0),重复上面工作即可。

class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
        if (prices.size() == 0)
            return 0;
        int minp = prices[0];
        int ret = 0;
        for (int i = 1; i < prices.size(); i++)
        {
            minp = min(minp, prices[i]);
            ret = max(ret, prices[i] - minp);
        }
        return ret; 
    }
};





122. Best Time to Buy and Sell Stock II

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

在同一天,可以先卖出,然后买入
way-1:
三种情况:
若今天是最后一天,只能卖
若今天比昨天价格低,而且不是昨天买的。那么就昨天卖,今天买入。
若今天比昨天价格低,是昨天买的,就改为今天买入。

way-2:

贪心算法,只要后一项比前一项大,就买入并于后一项卖出。


class Solution {
public:
    int maxProfit(vector<int>& price) 
    {
        //way-1
        
        int buy = 0;
        int yesterday = buy;
        int max = 0;
      
        for (int i = 1; i < price.size(); i++)
        {
            if (price[i] >= price[yesterday] && i == price.size() - 1)
            {
                max += price[i] - price[buy];
            }
            else if (price[i] < price[yesterday] && yesterday != buy)
            {
                max += price[yesterday] - price[buy];
                buy = i;
            }
            else if ( (price[i] < price[yesterday] && yesterday == buy) )
            {
                buy = i;
            }
            yesterday = i;
        }
        return max;   
          
        /* 
        //way-2
        if (price.size() < 2)  
            return 0;  
   
        int sum=0;  
        for (int i = 0; i < price.size() - 1; i++)
        {  
            if (price[i + 1] > price[i])
                sum += (price[i + 1] - price[i]);    
        }  
        return sum; 
        */
    }
};



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).

最多两次交易

用分治算法,以i为分界点,找出prices[0....i]的利润最大的交易。再找出prices[i.....length-1]的利润的最大交易。
遍历所有的i,找出利润最大的即可。
front[i]存的是i之前的一次交易最大收益
back[i]存的是i之后的一次交易最大收益

注意:求back[i]是从后往前搜索!


class Solution {
public:
    int maxProfit(vector<int>& prices) 
    {
       
        int length = prices.size();
        if (length < 2)
            return 0;
        int front[length] = {0};
        int back[length] = {0};
       
        int min1 = prices[0];
        for (int i = 1; i < length; i++)
        {
            min1 = min(min1, prices[i]);
            front[i] = max(front[i-1], prices[i] - min1);
        }
       
        int max1 = prices[length-1];
        for(int i = length - 2; i >= 0; i--)
        {
            max1 = max(max1, prices[i]);
            back[i] = max(back[i+1], max1 - prices[i]);
        }      
       
        int ret = 0;
        for (int i = 0; i < length; i++)
        {
            ret = max(ret, front[i] + back[i]);
        }
        return ret;
    }
};


188. Best Time to Buy and Sell Stock IV

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 k transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题目的关键是要写出下面的动态转移方程:
local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),
global[i][j]=max(local[i][j],global[i-1][j]),

这道题是Best Time to Buy and Sell  Stock的扩展,现在我们最多可以进行两次交易。
我们仍然使用动态规划来完成,事实上可以解决非常通用的情况,也就是最多进行k次交易的情况。

这里我们先解释最多可以进行k次交易的算法,然后最多进行两次我们只需要把k取成2即可。我们还是使用“局部最优和全局最优解法”。我们维护两种量,
一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),
另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。

下面我们来看递推式。
全局的比较简单,

global[i][j]=max(local[i][j],global[i-1][j]),

也就是去当前局部最好的,和过往全局最好的中大的那个(因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。
对于局部变量的维护,递推式是
local[i][j]=max(global[i-1][j-1]+max(diff,0), local[i-1][j]+diff)


也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,
如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),
第二个量则是取local第i-1天j次交易,然后加上今天的差值
(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,
而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。


上面的算法中对于天数需要一次扫描,而每次要对交易次数进行递推式求解,所以时间复杂度是O(n*k),如果是最多进行两次交易,那么复杂度还是O(n)。空间上只需要维护当天数据皆可以,所以是O(k),当k=2,则是O(1)。"


local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),
global[i][j]=max(local[i][j],global[i-1][j])


class Solution {
public:
    int maxProfit(int k, vector<int>& prices) 
    {
        if (prices.size() < 2 || k <= 0)
            return 0;
        if (k >= prices.size()) //退化为无限次
        {
            int ret=0;
            for(int i = 1; i < prices.size(); i++)
                if (prices[i] > prices[i-1])
                     ret += prices[i] - prices[i-1];
            return ret;
        }
         
        vector<vector<int>> local(prices.size(), vector<int> (k+1, 0));
        vector<vector<int>> global(prices.size(), vector<int> (k+1, 0));
         
        for (int j = 1; j <= k; j++)
        {
            for(int i = 1; i < prices.size(); i++)
            {
                int diff = prices[i] - prices[i-1];
                local[i][j] = max(global[i-1][j-1] + max(diff, 0), local[i-1][j] + diff);
                global[i][j] = max(global[i-1][j], local[i][j]);
            }
        }
        return global[prices.size()-1][k];
    }
};














  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值