C++ O(n) time O(1) space


  • 2
    E

    b is maximum value after a series of alternating buy-sell actions, starting with a buy and ending with a buy.
    c is maximum value after a series of alternating buy-sell actions, starting with a buy and ending with a sell.
    c is the answer to the problem.

    class Solution {
    public:
        int maxProfit(vector<int>& a, int f) {
            int n = a.size();
            int b = -a[0],c = 0;
            for (int i = 1; i < a.size(); ++i) {
                int nb = max(b, -a[i] + c);
                c = max(c, a[i] - f + b);
                b = nb;
            }
            return c;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.