best-time-to-buy-and-sell-stock-iii

题目描述

 

Say you have an array for which the i th 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).

思路:假设你现在手里的钱数为0。buy1,记录的是在从第1天到第i天你能买到的最低价格(买了,所以欠账,所以记录为负数,所以用max),sell1,记录的是在第1天到第i天中的某天,你卖出,能最多赚到多少钱。buy2和sell2有一个前提条件是你在第i天前,是否进行了第一次交易,如果进行了,那么用第一次交易的利润,在往下计算,这样你是带着第一次交易的利润,来计算的,所以接下来,如果你又进行了交易,那么就是2次交易的最大值。如果你在第i天前,没有进行交易,那么buy1和buy2其实是一样的,sell1和sell2是一样的,都没有变化。
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size()<=1)
            return 0;
        int buy1=INT_MIN;
        int sell1=0;//第一次卖时的利润
        int buy2=INT_MIN;
        int sell2=0;//第二次卖时的利润,也就是总利润
        for(int i=0;i<prices.size();++i)
        {
            buy1=max(buy1,-prices[i]);
            sell1=max(sell1,buy1+prices[i]);
            buy2=max(buy2,sell1-prices[i]);
            sell2=max(sell2,buy2+prices[i]);
        }
        return sell2;
    }
};

 

posted @ 2019-06-14 20:56  LJ的博客  阅读(184)  评论(0编辑  收藏  举报