哈哈哈哈或或或或或又是一道自己做出来的题目!!
开心开心
虽然方法很笨,但是好开心呀!!
思路:先判断如果只能交易一次的话最大值;存入max中;
再判断当前值是否小于下一个值,如果小于,则求差值,并存入sum中;
如果大于,则pass 继续寻找.
注意!!!!刚开始理解有误区,以为不可以再售出的时候再买入,
其实是可以的。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if prices==[]:
return 0
l=len(prices)
low=prices[0]
max=0
j=1
sum=0
for i in range(1,l):
if prices[i]<low:
low=prices[i]
else:
sub=prices[i]-low
if sub>max:
max=sub
while j<l:
if prices[j]<=prices[j-1]:
j+=1
else:
s=prices[j]-prices[j-1]
sum+=s
j+=1
if max>sum:
return max
else:
return sum
但是,参考了答案以后,发现最最聪明的做法下面这个!!!!
前方高能!
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
profit = 0
for i in range(1,len(prices)):
if prices[i] > prices[i-1]:
profit += prices[i]-prices[i-1]
return profit
---------------------
作者:神不烦
来源:CSDN
原文:https://blog.csdn.net/qq_34364995/article/details/80518177
版权声明:本文为博主原创文章,转载请附上博文链接!
比如[1,3,5,2,6,1,3]
profit=(3-1)+(5-3)+(6-2)+(3-1)=3-1+5-3+(6-2)+(3-1)=(5-1)+(6-2)+(3-1)