一、题目描述
二、解题思路
第二天的股票价格必须比第一天的价格多才能赚钱,相当于以第一天的价格买进,第二天的价格卖出
- 设 tmp 为第 i-1日买入与第 i 日卖出赚取的利润,即 tmp=prices[i] - prices[i-1];
- 当该天利润为正 tmp>0,则将利润加入总利润 profit;当 tmp<=0, 直接跳过;
- 遍历完成后,返回总利润 profit
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
profit=0
for i in range(1,len(prices)):
tmp=prices[i]-prices[i-1]
if tmp>0:
profit=tmp+profit
else:
i+=1
return profit