122. 买卖股票的最佳时机 II(贪心)
这道题只要明白,
Δ
P
i
m
a
x
=
p
n
−
p
1
=
(
p
2
−
p
1
)
+
(
p
3
−
p
2
)
+
.
.
.
+
(
p
n
−
p
n
−
1
)
\Delta P_{i\ max} = p_n - p_1=(p_2 - p_1)+(p_3 - p_2)+...+(p_n - p_{n-1})
ΔPi max=pn−p1=(p2−p1)+(p3−p2)+...+(pn−pn−1)
我们希望的卖出去之后有更大的收入,是可以通过每次上升去累加的,这样能够达到前后差值最大的效果。而每一个山谷到山顶的差值就是我们买卖的收益。下面来自官方视频题解的图片能够明显看出来
class Solution:
def maxProfit(self, prices: List[int]) -> int:
income = 0
for i in range(len(prices)-1):
if prices[i] < prices[i+1]:
income += prices[i+1] - prices[i]
return income
今天任务繁重,就这样吧。
记录一下昨晚的双周赛,首战没被甩到后50%hhh