122. Best Time to Buy and Sell Stock II

仍然是一个数组中一只股票是每天的价格,这次交易次数不做限制,求最大收益

思路:6 star, 从左到右遍历,如果当前比后面的一个数值大,则将当前和之前记录的较小值的差加到结果中,并设后面的为较小值,注意最后一个的边界条件

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""

length = len(prices)
if length <= 1:
return 0
low = prices[0]
index = 0
rs = 0
while index < length:
if index == length - 1:
if prices[index] > low:
rs += prices[index] - low
else:
if prices[index] > prices[index+1]:
rs += prices[index] - low
low = prices[index+1]
index += 1
return rs

Go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//也是分别计算各个递增区间的收益,然后加起来就是最后的收益,从左到右遍历,根据当前的值和前边的值大小对比,比前面大则计算当前收益,并继续向前
//比前边小则将上个区间的收益加到总收益中,并更新start和curProfit的值,start是当前递增区间的起始值,curProfit是当前递增区间的收益
func maxProfit(prices []int) int {
if len(prices) == 0 {return 0}
profit, curProfit := 0, 0
var start int
for index,val := range prices {
if index == 0 {
start = val
continue
}
if val >= prices[index-1] {
curProfit = val - start
} else {
start = val
profit += curProfit
curProfit = 0
}
}
profit += curProfit
return profit
}