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

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();  if (n <= 1) return 0;
        // s0: max profit when not holding any stock
        // s1: max profix when holding 1 stock
        int s0 = 0, s1 = - prices[0] - fee;
        for (int i = 1; i < prices.size(); i++) {
            int prev_s0 = s0;
            s0 = max(s0, s1 + prices[i]);
            s1 = max(s1, prev_s0 - prices[i] - fee);
        }
        return s0;
    }
};

 

posted @ 2018-06-03 15:26  JTechRoad  阅读(77)  评论(0)    收藏  举报