题目
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路
股票涨至局部最高点再卖。将价格分为一个个的递增区间,对于每个区间,区间首买入区间尾卖出。
[1,2,3,2,4],3-1 + 4-2 > 4-1
代码
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices==None or len(prices)<=1:
return 0
profit = 0
l = 0
while l < len(prices):
r = l
while r+1<len(prices) and prices[r+1]>prices[r]:
r += 1
if prices[r] > prices[l]:
profit = profit + prices[r] - prices[l]
l = r
else:
l += 1
return profit
网友评论