Skip to content

123. Best Time to Buy and Sell Stock III

难度:Hard

刷题内容

原题连接

  • https://leetcode.com/problems/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 (i.e., you must sell the stock before you buy again).

Example 1:

Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
             Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.
Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

˼·1 **- ʱ�临�Ӷ�: O(n^2)*- �ռ临�Ӷ�: O(n)***

��֮ǰ�IJ�ͬ�������Ҫ�������Σ内容描述�ü��仯�ķ�����¼�µ�i���֮���׵����ֵ������ǵڶ���ÿ�콻��֮������ֵ������ֻҪ�������飬�����һ�콻�����ֵ����һ内容描述ö����ÿ�ν��ף内容描述�ֵ��

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(!len)
            return 0;
        int arr[len + 1];
        memset(arr,0,sizeof(arr));
        int max1 = prices[len - 1],price = 0;
        for(int j = len - 2;j >= 0;--j)
        {
            if(prices[j] > max1)
                max1 = prices[j];
            arr[j] = max(arr[j + 1],max1 - prices[j]);
        }
        int ret = 0;
        for(int i = 0;i < len;++i)
            for(int j = i + 1;j < len;++j)
                if(prices[j] > prices[i])
                    ret = max(ret,prices[j] - prices[i] + arr[j + 1]);
        return ret;
    }
};

˼·2 **- ʱ�临�Ӷ�: O(n)*- �ռ临�Ӷ�: O(n)***

�ڶ��ַ������Ƕ�˼·1�������Ż内容描述һ�ν���ʱ����һ����Сֵmin1�������˵�i��֮ǰ����Сֵ��֮内容描述飬ÿ�θ���min1�����prices[i] - min1�����ֵ����

```cpp class Solution { public: int maxProfit(vector& prices) { int len = prices.size(); if(!len) return 0; int arr[len + 1]; memset(arr,0,sizeof(arr)); int max1 = prices[len - 1],price = 0; for(int j = len - 2;j >= 0;--j) { if(prices[j] > max1) max1 = prices[j]; arr[j] = max(arr[j + 1],max1 - prices[j]); } int ret = 0; int min1 = prices[0]; for(int i = 0;i < len;++i) { if(prices[i] < min1) min1 = prices[i]; ret = max(ret,prices[i] - min1 + arr[i + 1]); } return ret; } };



回到顶部