【一天一道LeetCode】#122. Best Time to Buy and Sell Stock II

时间:2021-07-14 08:49:45

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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

(二)解题

题目大意:相比于上题【一天一道LeetCode】#121. Best Time to Buy and Sell Stock来说,本题有多次买卖的机会。不过,买完之后卖了才能继续买。

解题思路:本题可以采用贪心算法,每次买卖都获取当前的最优值。

思路很简单,每次买卖取得利益最大化,即递增区间,一旦破坏了递增就卖,然后买下一个。遍历完了之后就获得了整体的利益最大化。

具体解释见代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int size = prices.size();
        int max = 0;
        for(int i = 0 ; i < size ; )
        {
            int j = i;
            while(j+1<size&&prices[j+1]>prices[j]) j++;//一旦破坏了递增就停下来
            if(j==i) i++;//一开始就不递增,就直接考虑下一个
            else {
                max+=prices[j]-prices[i];//计算当前最大利润,叠加到全部利润上
                i = j+1;//买下一个
            }
        }
        return max;
    }
};