首页 > 代码库 > 【LeetCode】Best Time to Buy and Sell Stock II

【LeetCode】Best Time to Buy and Sell Stock II

     题意:

    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).

     思路:

     要求可以多次转手买卖股票所能得到的最大收益。那么,在所有的股票价格变动的序列里,我只要找出所有的上升序列,在每一段单调上升序列的开始买入股票,结束时卖出股票,就可以得到股票价格上升的利润。

     那么,这些上升序列怎么求得呢?其实很简单,因为每一段上升序列都是由一个上涨的两天股票价格小区间组成,即是假如有 1 3 6 7 的上升序列,你只要看成  (1,3)、(3,6)、(6,7)的小序列构成,然后利润就是每个小区间的差值。简单说,就是只要遇到当前价格比前一天高,就加到总利润中去,最后的值就是所求答案。

     代码:

    C++:

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

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        n = len(prices)
        ans = 0
        for i in range(1,n):
            if prices[i] > prices[i-1]:
                ans += prices[i] - prices[i-1]
                
        return ans



【LeetCode】Best Time to Buy and Sell Stock II