leetcode 122. Best Time to Buy and Sell Stock II-股票交易|贪心算法

来源:互联网 发布:iphonese怎么样知乎 编辑:程序博客网 时间:2024/06/01 12:30
原题链接:122. Best Time to Buy and Sell Stock II

【思路-Java、Python】

假设每天最多可以进行2次交易(一次买,一次卖)。那么用贪心算法,

如果第 i 天相比第 i-1天有收益,那么就将收益放入到那么就在第 i-1 天买入股票(不管第 i-1 天是否持股,如果持股就卖出再买入),在第 i 天卖出。

如果第 i 天相比第 i-1 天没有收益,那么就在第 i-1当天卖出。(相当于没有买也没有卖)

这样就可以将所有收益收入囊中,获得最大收益。但是题目规定,不可以进行多次交易。我们认真分析,发现多次交易其实是出现在①(因为②没有收益,那么我就不买入,也不卖出,当天不进行交易)。而①会出现多次交易是因为第 i-1 天持股,而持股的原因是因为第 i-1天相对于第 i-2天有收益,那么这个连续的收益过程实际上是可以合并为一次,即第 i-2天买入,第 i 天卖出。所以我们分析时当天多次交易这个矛盾,在实际操作中是可以化解的:

public class Solution {    public int maxProfit(int[] prices) {        if (prices.length < 2) return 0;        int maxPro = 0, lastBuy = prices[0];        for (int i = 1; i < prices.length; i++) {            if (prices[i] > lastBuy) maxPro += prices[i] - lastBuy;            lastBuy = prices[i];        }        return maxPro;    }}
198 / 198 test cases passed. Runtime: 2 ms  Your runtime beats 15.31% of javasubmissions.

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        profit = 0;        for i in range(len(prices)-1) :            if (prices[i+1] > prices[i]) :                profit += prices[i+1] - prices[i];        return profit
198 / 198 test cases passed. Runtime: 56 ms  Your runtime beats 32.51% of pythonsubmissions.

1 0