先看一道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元钞票。

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

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

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

Algorithm - 贪心算法使用场景 ( LEETCODE —— Best Time to Buy and Sell Stock II)的更多相关文章

  1. 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 ...

  2. LeetCode: Best Time to Buy and Sell Stock II 解题报告

    Best Time to Buy and Sell Stock IIQuestion SolutionSay you have an array for which the ith element i ...

  3. [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 al ...

  4. LeetCode——Best Time to Buy and Sell Stock II (股票买卖时机问题2)

    问题: Say you have an array for which the ith element is the price of a given stock on day i. Design a ...

  5. [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 al ...

  6. LeetCode: Best Time to Buy and Sell Stock II [122]

    [题目] Say you have an array for which the ith element is the price of a given stock on day i. Design ...

  7. [leetcode]Best Time to Buy and Sell Stock II @ Python

    原题地址:https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 题意: Say you have an array ...

  8. LeetCode——Best Time to Buy and Sell Stock II

    Description: Say you have an array for which the ith element is the price of a given stock on day i. ...

  9. LeetCode OJ--Best Time to Buy and Sell Stock II

    http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ 第二问,是说可以进行无数次买卖. 贪心法 #include &l ...

随机推荐

  1. 安装vue

    node.js环境(npm包管理器) vue-cli 脚手架构建工具 cnpm npm的淘宝镜像 1) 安装node.js 从node.js官网下载并安装node,安装过程很简单,一直点下一步就ok了 ...

  2. HDU 2141 Can you find it? (二分)

    题目链接: Can you find it? Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/10000 K (Java/ ...

  3. linux文件系统初始化过程(5)---加载initrd(下)

    一.目的 linux把文件分为常规文件.目录文件.软链接文件.硬链接文件.特殊文件(设备文件.管道文件.socket文件等)几种类型,分别对应不同的新建函数sys_open().sys_mkdir() ...

  4. where语句中不能直接使用聚合函数

    1.问题描述 select deptno ,avg(sal) from emp where count(*)>3 group by deptno; 在where 句中使用聚合函数count(*) ...

  5. 阿里云linux服务器打开端口号

    之前linux回滚了下,然后就连不上xshell和filezille了,后台安全配置哪里也都打开了端口号了,还是不行.然后我就想重启下ssh服务 ,执行service sshd restart 提示1 ...

  6. flink 常见问题整理

    1. xml-apis 冲突问题 javax.xml.parsers.FactoryConfigurationError: Provider for class javax.xml.parsers.D ...

  7. 20145234黄斐《网络对抗技术》实验八、Web基础

    Apache 先通过apachectl start命令开启Apach,使用netstat -aptn命令查看端口占用: 因为端口号80已经被占用(上次实验设置的),所以先修改/etc/apache2/ ...

  8. 《图说VR入门》——Unity插件DK2使用教程

    本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/53339254 作者:car ...

  9. RAC建立过程回顾--建立用户和组

    一共需要建立6个组: oinstall dba asmadmin asmdba asmoper oper 要建立两个用户: oracle 和 grid 然后还要给各个用户建立各自的环境变量. 以下的操 ...

  10. 【HAOI2016】放棋子

    题面 题解 任意两个障碍不在同一列 要求你放$N$个棋子也满足每行只有一枚棋子,每列只有一枚棋子的限制. 这™不就是个错排吗??? $$ h_i=(n-1)(h_{i-1}+h_{i-2}),h_1= ...