LEETCODE —— Best Time to Buy and Sell Stock II [贪心算法]
先看一道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元钞票。
那么问题来了,在什么场景下使用贪心算法能获得最优解?
答:局部最优解能决定全局最优解。简单地说,问题能够分解成子问题来解决,子问题的最优解能递推到最终问题的最优解。
贪心法一般不能得到我们所要求的答案。一旦一个问题可以通过贪心法来解决,那么贪心法一般是解决这个问题的最好办法。由于贪心法的高效性以及其所求得的答案比较接近最优结果,贪心法也可以用作辅助算法或者直接解决一些要求结果不特别精确的问题。
LEETCODE —— Best Time to Buy and Sell Stock II [贪心算法]的更多相关文章
- [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 ...
- Algorithm - 贪心算法使用场景 ( LEETCODE —— Best Time to Buy and Sell Stock II)
先看一道leetcode题: Best Time to Buy and Sell Stock II Say you have an array for which the ith element is ...
- 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 ...
- [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 ...
- 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 ...
- [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 ...
- [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 ...
- 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 ...
- 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. ...
随机推荐
- Mac 在命令行中获得Root权限
Mac 在命令行中获得Root权限 作者 firedragonpzy 13 九月, 2012 2条评论 本文为firedragonpzy原创,转载务必在明显处注明:转载自[Softeware MyZo ...
- JAVA 使用POI导出数据格式为Execl
需要下载一个poi的jar包. 控制器 @Override public void getContractListExecl(Contract contract, BindingResult resu ...
- Unsupported major.minor version 51.0解决
http://blog.csdn.net/justdb/article/details/7850212 解决:项目------>右键------>属性------>Java Comp ...
- 数组的sort方法
今天在看<JavaScript高级程序设计第三版>时,学到了数组的sort方法.知道这个方法,但是一直没仔细研究过,这次发现,它是把数组内的值用toSting()变为字符串再进行比较,这样 ...
- 用c语言编写二分查找法
二分法的适用范围为有序数列,这方面很有局限性. #include<stdio.h> //二分查找法 void binary_search(int a[],int start,int mid ...
- postgres 查询数据库所有表名
select relname as TABLE_NAME ,col_description(c.oid, 0) as COMMENTS from pg_class cwhere relkind = ' ...
- 基于天天动听API开发在线音乐查询网站
预览图 源码下载 地址:https://github.com/bajdcc/dev/tree/master/ttpod 文件夹说明: App_Code,WCF服务 Script,离线下载的celery ...
- 删除桌面IE图标
B416D21B-3B22-B6D4-BBD3-BBD452DB3D5B HKEY_USERS\S-1-5-21-3567631753-1637826720-2857290141-500\Softwa ...
- linux下安装nginx后开机启动篇
众所周知nginx安装后需要手动去启动,每次开机之后都要执行nginx的启动命令很蛋疼.那么我们来让nginx开机启动吧 1.先創建一個nginx文件把 [root@localhost ~]# vi ...
- appcan.windw.open appcan.frame.open appcan.window.openPopOver evaluateScript
在模拟器上,几种发方式产生的窗口,其实都是iframe. 在根窗口(app打开的第一个)执行JS: try{ appcan.window.evaluateScript( { name: 'root', ...