1. 程式人生 > >letcode 714. Best Time to Buy and Sell Stock with Transaction Fee

letcode 714. Best Time to Buy and Sell Stock with Transaction Fee

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

Example 1:

Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
Buying at prices[0] = 1
Selling at prices[3] = 8
Buying at prices[4] = 4
Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note: 0 < prices.length <= 50000. 0 < prices[i] < 50000. 0 <= fee < 50000.

給定一個數組,陣列中的第i個元素為一隻股票第i天的價格。現在求買賣股票所能得到的最大值。 如果用貪心的思想去解這道題,應注意 貪心選擇 與 產生的子問題無關。因此,只能確定應該在何時買入,而無法確定何時賣出(因為沒有標準去衡量賺多少錢是最優的)。所以,我們需要制定一個判斷標準去衡量應該在何時買入。 如果對於一個單調上升的數列,其最優解必然是 最大值 - 最小值 。但如果指定的區間內不是單調上升的,那麼假定存在一個 比區間最小值大的某個值,和 比區間最大值小的某個值 ,能將這個區間分成兩部分,並且使這兩部分的各自的 最大值 - 最小值 的和 大於 原區間 最大值 - 最小值。 在這裡插入圖片描述

這樣,從左側開始遍歷陣列,按照選擇買入的判斷標準,不斷將原有區間細分,最終求得最優解

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int len=prices.size();
        if(len==0 || len==1)
            return 0;
        int sum=0;
        int peak=0;
        int least=INT_MAX;
        for(auto ele : prices){
            if(peak-ele>fee){
                sum+=(peak-least-fee);
                least=ele;
                peak=0;
            }
            least=min(ele,least);
            if(ele-least>fee){
                peak=max(peak,ele);
            }
        }
        if(peak-least>fee)
            sum+=(peak-least-fee);
        return sum;
    }
};

注意:

  1. 由於是判斷何時買入,所以在執行買入前先執行賣出操作
  2. 賣出操作時注意對下個區間最大值和最小值的初始化
  3. 由於判斷何時買入,在沒有新的買入前不進行賣出,因此在迴圈結束時,要進行最後一次賣出