LeetCode122——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 (i.e., buy one and sell one share of the stock multiple times). Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
理解:
假设你有个数组,其中第i个元素是第i天的股票价格,请设计一种算法去找到最大的收益,你可以用任何你喜欢的方式完成交易(多次买入或卖出股票权)。
注意:你不能在同一时间完成多次交易,你必须再次买入这支股票以后才能卖出。
例子1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
例子2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
例子3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0. 原始解题思路:
要获得最好的收益,就要坚持“低吸高抛”,所以只需要比较当前日的股价与下一日的股价,如果下一日的股价高于本日,那就购买,计算收益(此时为负数),否则继续等待。
第二天继续比较第二天与第三天的股价,如果第三天高于第二天,则购买(此时相当于持有不做出操作,设置一个标志符表示当前是已买入还是已卖出),如果第三天低于第二天的股价,则卖出。 python代码:
class Solution:
def maxProfit(self, prices):
trans_flag = 0 # 0 表示未购买或者已卖出,1 表示已购买未卖出
profit = 0
end_day = len(prices)
if end_day < 2:
print("总收益:{}".format(profit))
return 0
for i in range(end_day - 1):
if prices[i] < prices[i + 1] and trans_flag == 0:
print("买入第{}天的股票".format(i + 1))
trans_flag = 1
current_i = i
profit -= prices[i]
continue
if prices[i] < prices[i + 1] and trans_flag == 1:
print("继续持有股票")
continue
if prices[i] > prices[i + 1] and trans_flag == 1:
print("卖出第{}天的股票".format(i + 1))
profit += prices[i]
current_i = 0
trans_flag = 0
continue
if prices[i] > prices[i + 1] and trans_flag == 0:
print("暂不购买")
continue
print("当前收益:{}".format(profit))
# 第一个问题:这里加一步验证一直持有到最后一天未卖出,所以收益没计算完全的问题,同时要小心很小的数据集,比如只有一个
# 第二个问题:与上一天比较时不一定要大于,可能两者相等
if prices[end_day - 1] >= prices[end_day - 2] and trans_flag == 1:
trans_flag = 1
profit += prices[end_day - 1]
print("总收益:{}".format(profit))
if __name__ == '__main__':
prices1 = [7, 1, 5, 3, 6, 4]
prices2 = [1, 2, 3, 4, 5]
prices3 = [7, 6, 4, 3, 1]
prices4 = [2,3]
prices5 = [1,9,6,9,1,7,1,1,5,9,9,9]
Mine = Solution()
Mine.maxProfit(prices5)
验证结果:
class Solution:
def maxProfit2(self, prices):
print(sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1)))
验证结果:
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 返回一个对象
>>> zipped
<zip object at 0x103abc288>
>>> list(zipped) # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c)) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)] >>> a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]
>>>
在这里就是将range函数变为迭代器,每次从prices的当前位置和下一个位置取出x和y,然后依然判断求和
class Solution:
def maxProfit(self, prices):
return sum([y - x for x, y in zip(prices[:-1], prices[1:]) if x < y])
class Solution:
def maxProfit(self, prices):
return(sum(prices[i + 1] - prices[i] for i in range(len(prices) - 1) if prices[i + 1] > prices[i]))
结果:
所以想提高,还是要学一下迭代器的应用啊。
LeetCode122——Best Time to Buy and Sell Stock II的更多相关文章
- Leetcode-122 Best Time to Buy and Sell Stock II
#122 Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the pric ...
- LeetCode122: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 a ...
- [LintCode] 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 [贪心算法]
Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price of a ...
- 27. Best Time to Buy and Sell Stock && Best Time to Buy and Sell Stock II && Best Time to Buy and Sell Stock III
Best Time to Buy and Sell Stock (onlineJudge: https://oj.leetcode.com/problems/best-time-to-buy-and- ...
- 【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 ...
- 31. leetcode 122. Best Time to Buy and Sell Stock II
122. Best Time to Buy and Sell Stock II Say you have an array for which the ith element is the price ...
- 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 ...
- 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 ...
随机推荐
- Java匹马行天下之 Java国出了个Java——举国欢庆
Java帝国的崛起 前言: 看庭前花开花落,宠辱不惊, 望天上云卷云舒,去留无意. 闹心的事儿,选择释怀: 纠缠的人儿,试着放下, 生活其实很美. 心若向阳,就无惧悲伤. 愿你明朗坦荡纵情豁达,有得有 ...
- Java常识及数据类型
上次介绍完了JDK的下载,安装,以及配置了环境变量 .这次我们来讲讲Java的常识及Java的数据类型; 常见Java开发工具 编辑器: 1:UltraEdit; 2:EditPlus等; 集成开发环 ...
- BUG 的生命周期
BUG 的生命周期 Bug-->软件程序的漏洞或缺陷 Bug 的类型:代码错误.设计缺陷.界面优化.性能问题.配置相关.安装部署.安全相关.标准规划.测试脚本....其他(功能类.界面类.性能类 ...
- C语言入门-数据类型
一.C语言的类型 整数:char.short.int.long.longlong 浮点型:float.double.long double 逻辑:bool 指针 自定义类型 类型有何不同 类型名称:i ...
- git远程操作相关命令(remote 、push、fetch 、pull)
git remote 为了便于管理,Git要求每个远程主机都必须指定一个主机名.为了便于管理,Git要求每个远程主机都必须指定一个主机名. git remote[查看创库名] git remote 在 ...
- Centos7 快速安装Docker
写在前面 Docker是一个开源的引擎,可以轻松的为任何应用创建一个轻量级的.可移植的.自给自足的容器.开发者在笔记本上编译测试通过的容器可以轻松批量地在生产环境中部署. 网上的安装教程也很多这里我推 ...
- Spring 梳理-AOP
界面应用场景 日志.声明式事务.安全.缓存 AOP功能演化图 图片引用地址:https://www.cnblogs.com/best/p/5679656.html AOP设计模式-代理模式 静态代理: ...
- 2019年最新超级有趣好玩的html+css网页布局课程,前端入门基础,html5+css3零基础入门课程-黑马程序员pink老师精心录制
大家好,我是黑马程序员pink老师!! 本次视频是前端零基础入门的课程,pink老师采取有趣好玩讲法,带你快乐的学习枯燥的html+css知识,学完之后让你能快速布局pc端页面.代码也可以讲的好玩有趣 ...
- Thinkphp5.0第二篇
查询构造器 //插入记录 $result=Db::table('think_data')->insert(['name'=>'张三','status'=>1]); //修改数据 $r ...
- C++学习笔记二、头文件与源文件
头文件 .h 与源文件 .ccp 的区别 .h 文件一般是用来定义的,比如定义函数.类.结构体等: .cpp 文件则是对头文件的定义进行实现. include .h文件,可以调用你声明的函数.类等.当 ...