先看一道leetcode題:算法
Best Time to Buy and Sell Stock IIapp
Say you have an array for which the ith element is the price of a given stock on day i.spa
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). 貪心實現以下:code
''' 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) self.trade(prices) return self.profit def __init__(self): self.profit = 0 self.bought = 0 def trade(self, prices): 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)
貪心算法的特色是一條路走到黑,把問題分解成若干子問題,逐個解決,問題集愈來愈小直到全解完,這時結果集就認爲是最優解。blog
但貪心算法並不能在全部場景下確保結果是最優解,在一些狀況下結果是次優解,看這個問題:ip
假如某個國家只有1元、5元和11元面值的鈔票,這時若是有商人要【找零15元】,問最少鈔票張數?element
假如使用貪心算法,則結果爲一張11元和4張1元鈔票,共5張。而實際正確結果應該爲3張5元鈔票。leetcode
那麼問題來了,在什麼場景下使用貪心算法能得到最優解?it
答:局部最優解能決定全局最優解。簡單地說,問題可以分解成子問題來解決,子問題的最優解能遞推到最終問題的最優解。io
貪心法通常不能獲得咱們所要求的答案。一旦一個問題能夠經過貪心法來解決,那麼貪心法通常是解決這個問題的最好辦法。因爲貪心法的高效性以及其所求得的答案比較接近最優結果,貪心法也能夠用做輔助算法或者直接解決一些要求結果不特別精確的問題。