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).
核心是:唯利是图。 因为可以多次交易,只要有价格差(还是只有后期价格大于前期),就可以交易,就可以积累利润。所以遍历价格list,只有后面的价格比前面的高,就可以有利润。如果没有前面高,那么不交易就行,利润当个时间段为0
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
profit = 0
for i in xrange(1, len(prices)):
if prices[i] > prices[i-1] :
profit += prices[i] - prices[i-1]
return profit