122. Best Time to Buy and Sell Stock II

题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
题目tag:Array,Greedy
此题中,由于可以无限次进行交易,我们只需找出所有能赚钱的交易即可。

naive example

如图所示的例子中,总共有5天的价格,我们只需找出红色的两段,并将利润相加,即是我们要的答案。换言之,找出所有上升的区间,并将利润相加即可,用伪代码来描述:

初始化利润 p=0
遍历prices:
  找到local minimum p_min
  找到local maximum p_max
  更新p,p += p_max - p_min
返回 p

res = prices[1] - prices[0] + prices[3] - prices[2]
我们再看这样一个例子

naive example 2

实际的价格可能是这样的,会有连续上升的价格段。这启发我们用一个有一点小技巧的算法:

初始化利润 p=0
遍历prices:
  得到前一天价格 p_previous
  得到当前的价格 p_now
  if p_now - p_previous > 0:
    p += p_now - p_previous
返回 p

python代码:

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        n = len(prices)
        buy = prices[0]
        res = 0
        for i in range(1, n):
            if prices[i] > buy:
                res += prices[i] - buy
            buy = prices[i]
        return res

Java代码:

class Solution {
    public int maxProfit(int[] prices) {
        int res = 0;
        for (int i=1; i<prices.length; i++){
            int previous = prices[i-1];
            int now = prices[i];
            if((now-previous) > 0){
                res += now-previous;
            }
        }
        return res;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容