【LeetCode】122. Best Time to Buy and Sell Stock II


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

 

核心思想:每一段单调递增区间的收益累加。

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM