# Algorithm - 贪心算法使用场景 （ LEETCODE —— Best Time to Buy and Sell Stock II）

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). 贪心实现如下：

'''
Created on Nov 13, 2014
@author: ScottGu<gu.kai.66@gmail.com, kai.gu@live.com>
'''
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
self.__init__()
for i in range(len(prices)):
prices[i] = prices[i] + 1
prices.append(0)

return self.profit
def __init__(self):
self.profit = 0
self.bought = 0
if (prices == None):
return
for i in range(1, len(prices) - 1):
if (prices[i - 1] < prices[i] >= prices[i + 1]):  # sell
if (self.bought == 0): self.bought = prices[i - 1]
self.profit += (prices[i] - self.bought)
self.bought = 0

if (prices[i - 1] >= prices[i] < prices[i + 1]):  # buy
self.bought = prices[i]

if (prices[i - 1] < prices[i] < prices[i + 1]):  # maybe buy
if (self.bought == 0): self.bought = prices[i - 1]
if (self.bought > 0):
self.profit += (prices[-1] - self.bought)

if __name__ == '__main__':
so = Solution()
# test cases:
prices = [1, 2, 3, 4, 5, 3, 3, 3, 2, 6, 7, 3, 4]
print prices
print so.maxProfit(prices)
# case 2
prices = [1, 2]
print prices
print so.maxProfit(prices)
# case 3
prices = [2, 2, 5]
print prices
print so.maxProfit(prices)

贪心算法的特点是一条路走到黑，把问题分解成若干子问题，逐个解决，问题集越来越小直到全解完，这时结果集就认为是最优解。

假如某个国家只有1元、5元和11元面值的钞票，这时如果有商人要【找零15元】，问最少钞票张数？

假如使用贪心算法，则结果为一张11元和4张1元钞票，共5张。而实际正确结果应该为3张5元钞票。

-- Scott, Programmer in Beijing [If you can’t explain it to a six year old, you don’t understand it yourself. —Albert Einstein ]
posted @ 2014-11-15 00:00  ScottGu  阅读(996)  评论(0编辑  收藏  举报