122. Best Time to Buy and Sell Stock II
很有意思的一道题目
怎么利益最大化?
贪婪算法就是要把问题分解成小问题,把全局最优集问题分为一个个局部最优解的小问题。
那么把全局利益最大化,转换为当前的局部利益最大,当第二天比第一天价格高的时候就第一天买和第二天卖,当第二天比第一天价格低的时候就不动。
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:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
ans = 0
for i in range(len(prices) -1):
if prices[i] < prices[i+1]:
ans += prices[i+1] - prices[i]
return ans