给定一个数组 prices 表示一支股票每天的价格.
你可以完成任意次数的交易, 不过你不能同时参与多个交易 (也就是说, 如果你已经持有这支股票, 在再次购买之前, 你必须先卖掉它).
设计一个算法求出最大的利润.
class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
maxprofit = 0
for i in range(len(prices) - 1):
if prices[i + 1] > prices[i]:
maxprofit = maxprofit + prices[i + 1] - prices[i]
return maxprofit
贪心法: 只要相邻的两天股票的价格是上升的, 我们就进行一次交易, 获得一定利润.
其实就是统计所有相邻元素是升的的差值之和。来自:https://www.lintcode.com/problem/best-time-to-buy-and-sell-stock-ii/note/177787
假如为[1,2,3,4],可以理解为1买入,2卖出。2买入,3卖出。3买入,4卖出。只要相邻是升就买卖。实际同一天内买入卖出可以抵消。最终为1买入,4卖出。