【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