zoukankan      html  css  js  c++  java
  • Algorithm

    先看一道leetcode题:

    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)
    
            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)

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

    但贪心算法并不能在所有场景下确保结果是最优解,在一些情况下结果是次优解,看这个问题:

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

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

    那么问题来了,在什么场景下使用贪心算法能获得最优解?

    答:局部最优解能决定全局最优解。简单地说,问题能够分解成子问题来解决,子问题的最优解能递推到最终问题的最优解。

    贪心法一般不能得到我们所要求的答案。一旦一个问题可以通过贪心法来解决,那么贪心法一般是解决这个问题的最好办法。由于贪心法的高效性以及其所求得的答案比较接近最优结果,贪心法也可以用作辅助算法或者直接解决一些要求结果不特别精确的问题。

  • 相关阅读:
    java中会存在内存泄漏吗,请简单描述?
    垃圾回收器的基本原理是什么?垃圾回收器可以马上回收内存吗?有什么办法主动通知虚拟机进行垃圾回收?
    SpringMvc的控制器是不是单例模式,如果是,有什么问题,怎么解决?
    SpringMVC怎么样设定重定向和转发的?
    Spring MVC的异常处理 ?
    如果前台有很多个参数传入,并且这些参数都是一个对象的,那么怎么样快速得到这个对象?
    Spring是什么?
    SpringMvc用什么对象从后台向前台传递数据的?
    SpringMvc中函数的返回值是什么?
    BeanFactory和ApplicationContext有什么区别?
  • 原文地址:https://www.cnblogs.com/scottgu/p/4098572.html
Copyright © 2011-2022 走看看