博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
122. Best Time to Buy and Sell Stock II [medium] (Python)
阅读量:2443 次
发布时间:2019-05-10

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

题目链接

题目原文

Say you have an array for which the ith element is the price of a given stock on day i <script type="math/tex" id="MathJax-Element-2">i</script>.

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

思路方法

思路一

额。。。虽说这题是贪心算法的应用,不过稍微还是简单了点。就怕想的太复杂,实际上只要能挣钱就买入卖出即可。

代码

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        res = 0        for i in xrange(1, len(prices)):            if prices[i-1] < prices[i]:                res += prices[i] - prices[i-1]        return res

思路二

按照对题目的理解,对于类似[1,2,3,0]这样的序列,最正确的做法是“1元买入3元卖出”。而上面的解法感觉像是“1元买入2元卖出,2元买入3元卖出”,当然,结果是对的,而且其实上面的解法相当于代码优化。比较繁一点的解法是“先找局部最小,再找局部最大”这样的循环,代码如下:

代码

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        res = 0        i = 0        while i < len(prices):            while i < len(prices)-1 and prices[i+1] <= prices[i]:                i += 1            j = i + 1            while j < len(prices)-1 and prices[j+1] >= prices[j]:                j += 1            res += prices[j] - prices[i] if j < len(prices) else 0            i = j + 1        return res

PS: 写错了或者写的不清楚请帮忙指出,谢谢!

转载请注明:

你可能感兴趣的文章
Linux系统可卸载内核模块完全指南(下)(转)
查看>>
思考-两个大表的关联.txt
查看>>
WIDTH_BUCKET和NTILE函数.txt
查看>>
sql plan baseline(二)
查看>>
第十章 sqlplus的安全性
查看>>
第十三章 sqlplus命令(一)
查看>>
第三章(backup and recovery 笔记)
查看>>
第一章(backup and recovery 笔记)
查看>>
第六章(backup and recovery 笔记)
查看>>
oracle备份功能简述
查看>>
[转]数据库三大范式
查看>>
恢复编录的创建和使用.txt
查看>>
truncate 命令使用
查看>>
[script]P_CHECK_BLACK.sql 检查当前用户下是否有varchar2字段的末尾包含空格
查看>>
实验-数据分布对执行计划的影响.txt
查看>>
实验-闪回数据库
查看>>
实验-闪回表
查看>>
oracle审计
查看>>
日期格式的转换
查看>>
游戏契合度提示音_产品/市场契合度
查看>>