LeetCode 122. Best Time to Buy and Sell Stock II (stock problem)

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

分析

参考stock problem相关的精帖

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()<=1) 
            return 0;
        vector<int> sell(prices.size(),0),buy(prices.size(),0);
        buy[0]=-prices[0];
        for(int i=1;i<prices.size();i++){
            sell[i]=max(sell[i-1],buy[i-1]+prices[i]);
            buy[i]=max(buy[i-1],sell[i-1]-prices[i]);
        }
        return sell[prices.size()-1];
    }
};

posted @ 2018-12-02 22:06  A-Little-Nut  阅读(102)  评论(0编辑  收藏  举报