博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
lc122. Best Time to Buy and Sell Stock II
阅读量:6537 次
发布时间:2019-06-24

本文共 1428 字,大约阅读时间需要 4 分钟。

  1. Best Time to Buy and Sell Stock II Easy

1015

1299

Favorite

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

Example 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. Example 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. Example 3:

Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.

思路:StefanPochmann大神,跪了,sum(b-a for a,b in zip(prices,prices[1:]) if a<b)

代码:python3

class Solution:    def maxProfit(self, prices: List[int]) -> int:        return sum(b-a for a,b in zip(prices,prices[1:]) if a

tips:

zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。复制代码

转载于:https://juejin.im/post/5d09a15c6fb9a07f0a2de3de

你可能感兴趣的文章
程序员提高工作效率的15个技巧【Facebook】
查看>>
ffmpeg+SDL2实现的视频播放器「退出、暂停、播放」
查看>>
2011/7/3 第二次评审
查看>>
Openvswitch手册(2): OpenFlow Controller
查看>>
Cocos2d-JS项目之二:studio基础控件的使用
查看>>
tar解压
查看>>
oracle中创建dblink
查看>>
inheritprototype原型继承封装及综合继承最简实例
查看>>
【磁耦隔离接口转换器】系列产品选型指南
查看>>
Apriori 关联算法学习
查看>>
二叉树、红黑树、伸展树、B树、B+树
查看>>
Junit核心——测试集(TestSuite)
查看>>
MVPArms官方首发一键生成组件化,体验纯傻瓜式组件化开发
查看>>
Log4j_学习_00_资源帖
查看>>
制作iso镜像U盘自动化安装linux系统
查看>>
JSLint的使用
查看>>
命令行常用命令--软连接
查看>>
关于SpringMVC中如何把查询数据全转成String类型
查看>>
tomcat运行错误
查看>>
HTTP POST GET 本质区别详解
查看>>