博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode By Python]121. Best Time to Buy and Sell Stock
阅读量:4054 次
发布时间:2019-05-25

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

题目:


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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

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

解释:其实这题和之前求最大字串有点类似,不过这是一个实际问题,就是要求买入必须在卖出之前

代码:

class Solution(object):    def maxProfit(self, prices):        """        :type prices: List[int]        :rtype: int        """        if prices==[]:            return 0        buyin = prices[0]; maxprofit = 0        for i in range(1,len(prices)):            currproift = prices[i]-buyin             if currproift>maxprofit:                maxprofit = currproift            if currproift<=0:                buyin = prices[i]        return maxprofita = Solution()print a.maxProfit([7, 6, 4, 3, 1])

转载地址:http://mzhci.baihongyu.com/

你可能感兴趣的文章
在C++中使用Lua
查看>>
socket编程中select的使用
查看>>
所谓的进步和提升,就是完成认知升级
查看>>
长文干货:如何轻松应对工作中最棘手的13种场景?
查看>>
如何用好碎片化时间,让思维更有效率?
查看>>
No.174 - LeetCode1305 - 合并两个搜索树
查看>>
No.175 - LeetCode1306
查看>>
No.182 - LeetCode1325 - C指针的魅力
查看>>
mysql:sql alter database修改数据库字符集
查看>>
mysql:sql truncate (清除表数据)
查看>>
yuv to rgb 转换失败呀。天呀。谁来帮帮我呀。
查看>>
驱动TFT要SDRAM做为显示缓存
查看>>
使用file查看可执行文件的平台性,x86 or arm ?
查看>>
qt 创建异形窗体
查看>>
简单Linux C线程池
查看>>
内存池
查看>>
ipconfig,ifconfig,iwconfig
查看>>
opensuse12.2 PL2303 minicom
查看>>
网络视频服务器移植
查看>>
Encoding Schemes
查看>>