题目

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

代码:oj测试通过 Runtime: 71 ms

 class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
# none case or one element case
if prices is None or len(prices)<2 :
return 0
# dp
buy = 0
sell = 0
profit = 0
for i in range(len(prices)-1):
if prices[i]<=prices[i+1]:
sell = i+1
else:
profit = profit + prices[sell]-prices[buy]
buy = i+1
sell = i+1
return profit+max(0,prices[sell]-prices[buy])

思路

采用贪心算法。

代码的逻辑还算清晰:找到最长的上升区间,最低卖最高买即可;然后再找下一个上升区间;退出循环的时候注意处理一下最后一个上升或下降区间。

for循环:

1. if的部分就是不断找更大的上升空间,找到了就一定把sell放在更利润的卖点。

2. else的部分处理的是价格下降的情况,buy和sell需要同时跟进,这样保证同样的买卖价格,做到不赔钱

有一个梗:代码AC后,我review时发现if和else里面都有sell=i+1这个语句,那么既然不管是if或else都得执行sell=i+1,为啥还要在每个语句里面单拎出来呢?于是就有了下面的代码(这部分代码是错误举例用的):结果竟然是报错。

            sell = i+1
if prices[i]>prices[i+1]:
profit = profit + prices[sell]-prices[buy]
buy = i+1

这是一个思维的陷阱:不错,确实在if和else里面都执行了sell=i+1这个语句,但是语句执行的逻辑顺序是不一样的。请注意,如果是prices[i]>prices[i+1]的条件下,sell=i+1是在profit语句之后执行的。于是恍然大悟,修改成如下的代码:

oj测试通过 Runtime: 67 ms

class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
# none case or one element case
if prices is None or len(prices)<2 :
return 0
# dp
buy = 0
sell = 0
profit = 0
for i in range(len(prices)-1):
if prices[i]>prices[i+1]:
profit = profit + prices[sell]-prices[buy]
buy = i+1
sell = i+1
return profit+max(0,prices[sell]-prices[buy])

这样代码的逻辑就更简洁了,可以解释如下:只要相邻两天,后一天比前一天高就可以低买高卖产生利润。

第二个更简洁的代码,似乎也是网上更多的人列出来的答案。简洁的解法也可以由一般的解法推演出来。

leetcode 【 Best Time to Buy and Sell Stock II 】python 实现的更多相关文章

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

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

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

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

  5. 122. Best Time to Buy and Sell Stock II@python

    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 买股票的最佳时间之二

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

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

  8. [leetcode]Best Time to Buy and Sell Stock III @ Python

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

  9. [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 ...

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

随机推荐

  1. Jscript 命名规范

    变量命名都以类型前缀+有意义的单词组成,用驼峰式命名法增加变量和函式的可读性.例如:sUserName,nCount. 前缀规范:每个局部变量都需要有一个类型前缀,按照类型可以分为:s:表示字符串.例 ...

  2. meterpreter > migrate 1548

    1548  1500  explorer.exe      x86   0           LIXIULI-VCS86VR\test      C:\WINDOWS\Explorer.EXE 19 ...

  3. Redis 优缺点

    REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统. Redis是一个开源的使用ANSI C语言编写.遵守B ...

  4. linux打开文件数测试

    /proc/sys/kernel/threads-max 系统最大线程数量 /proc/sys/vm/max_map_count 限制一个进程可以拥有的VMA(虚拟内存区域)的数量 /proc/sys ...

  5. Element-ui多选下拉实现全部与其他互斥

    1.以事件类型为例,给下拉绑定选项改变的change事件 2.当已选项个数大于1(即先选了其他,再选不限)且最后选的是不限时,取消其他选项选中状态: 当已选项个数等于2(即先选了不限,再选其他)且第一 ...

  6. POJ1061 青蛙的约会 __一维世界的爱情

    由于今天上午在做数论知识的笔记,发现那时候赵老师讲的线性丢番图(求ax+by=c的特解)部分完全搞不懂,后来网上查了一下才发现这个公式就是求同余方程,所用方法就是扩展欧几里得算法.正好红皮书上有这么一 ...

  7. EF写统计

    EF的特性是,你from的第一个表为主表,接下来的所有表以左联或者内联或者交叉连接的方式去显示,不会出现右联, 在编写的时候,可以先确定个数据源,然后对这个数据源进行数据的统计, 例如SQL: -- ...

  8. Java操作Redis工具类

    依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...

  9. CUDA常见问题与解答

    源 1.在SDK自带的例子程序中,发现SRC文件珜下有.cpp文件和.cu文件.这两种文件的关系和各自的作用是什么呀? 答:SDK自带例子中的.cpp文件主要是一些CPU端处理,或者是使用CPU计算对 ...

  10. Sum All Primes-freecodecamp算法题目

    Sum All Primes 1.要求 求小于等于给定数值的质数之和. 只有 1 和它本身两个约数的数叫质数.例如,2 是质数,因为它只能被 1 和 2 整除.1 不是质数,因为它只能被自身整除. 2 ...