题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
题目tag:Array,Greedy
此题中,由于可以无限次进行交易,我们只需找出所有能赚钱的交易即可。
如图所示的例子中,总共有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]
我们再看这样一个例子
实际的价格可能是这样的,会有连续上升的价格段。这启发我们用一个有一点小技巧的算法:
初始化利润 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 0){
res += now-previous;
}
}
return res;
}
}