Best Time to Buy and Sell Stock with Transaction Fee[LeetCode 714]

来源:互联网 发布:商家给淘宝消费积分 编辑:程序博客网 时间:2024/05/21 10:48

Ans


#include <iostream>#include <vector>#include <cstring>using namespace std;class Solution {public:    int maxProfit(vector<int>& prices, int fee) {        int size = prices.size();        vector <int> hold(size, 0), sold(size, 0);        haveStock[0] = -prices[0]; //have stock        haveNothing[0] = INT_MIN;    //nothing        for (int i = 1; i < size; i++) {            haveStock[i] = max(haveStock[i - 1], haveNothing[i - 1] - prices[i]); //have stock, i-1th rest or buy            haveNothing[i] = max(haveNothing[i - 1], haveStock[i - 1] + prices[i] - fee); // nothing, i-1th rest or sell            //cout << haveStock[i] << ' ' << haveNothing[i] << endl;        }        return haveNothing[size - 1];    }};int main() {    int prices1[] = {1, 3, 2, 8, 4, 9};    vector <int> prices(begin(prices1), end(prices1));    int fee = 2;    Solution a;    int b = a.maxProfit(prices, fee);    cout << b;    return 0;}

空间可以压缩为O(1),代码如下:

#include <iostream>#include <vector>#include <cstring>using namespace std;class Solution {public:    int maxProfit(vector<int>& prices, int fee) {        int size = prices.size();        //vector <int> hold(size, 0), sold(size, 0);        int haveStock = -prices[0]; //have stock        int haveNothing = 0;    //nothing        int temp = 0;        for (int i = 1; i < size; i++) {            temp = haveStock;            haveStock = max(haveStock, haveNothing - prices[i]); //have stock, i-1th rest or buy            haveNothing = max(haveNothing, temp + prices[i] - fee); // nothing, i-1th rest or sell            //cout << haveStock[i] << ' ' << haveNothing[i] << endl;        }        return haveNothing;    }};int main() {    int prices1[] = {1, 3, 2, 8, 4, 9};    vector <int> prices(begin(prices1), end(prices1));    int fee = 2;    Solution a;    int b = a.maxProfit(prices, fee);    cout << b;    return 0;}
阅读全文
0 0
原创粉丝点击