# 题目链接
# 题目描述
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
1
2
3
4
2
3
4
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
1
2
3
2
3
# 解题思路
- len(prices) <= 1 时,无法获利,返回 0
- 设每次股票价格上升区间内可能的累积收益 s:
- 当 s == 0 时,有增值即假设买入
- 当 s > 0 时,表示已买入并产生正收益,无论增值或贬值均计算收益并记录最大值 max
func maxProfit(prices []int) int {
if len(prices) <= 1 {
return 0
}
s, max := 0, 0
for i := 1; i < len(prices); i++ {
if prices[i] > prices[i-1] || s > 0 {
s += (prices[i] - prices[i-1])
if s < 0 {
s = 0
} else if s > max {
max = s
}
}
}
return max
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17