1.题目
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).
2. 分析
从价格表的极小点买入,从价格表的极大点卖出,即可获得最大利润。
3.代码
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if len(prices) < 2:
return 0
total = 0
buy = prices[0]
sell = 0
cond_buy = True;
for i in range(1,len(prices)):
if( cond_buy):
if(prices[i] <= prices[i-1]):
buy = prices[i]
else:
cond_buy = False;
sell = prices[i];
else:
if(prices[i] >= prices[i-1]):
sell = prices[i];
else:
total += sell - buy;
cond_buy = True;
buy = prices[i]
if (not cond_buy):
total += sell - buy;
return total