【LeetCode with Python】 Best Time to Buy and Sell Stockd
来源:互联网 发布:sql删除数据库字段 编辑:程序博客网 时间:2024/06/16 08:18
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: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): if None==prices or len(prices)<2: return 0 min=prices[0] # print len(prices) max_diff=0 for i in range(1,len(prices)): if prices[i-1]<min: #因为一定买的比卖的贵 min=prices[i-1] print min # print i # print prices[i-1] cur_diff=prices[i-1]-min if cur_diff>max_diff: max_diff = cur_diff return max_diffprices=[82,2,44,1,1,3,2,7,4,5,7,6]print Solution().maxProfit(prices)
0 0
- 【LeetCode with Python】 Best Time to Buy and Sell Stockd
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- leetcode Best Time to Buy and Sell Stock with Cooldown
- LeetCode Best Time to Buy and Sell Stock with Cooldown
- Leetcode: Best Time to Buy and Sell Stock with Cooldown
- [LeetCode]Best Time to Buy and Sell Stock with Cooldown
- Leetcode Best Time to Buy and Sell Stock with Cooldown
- leetcode - Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- leetcode Best Time to Buy and Sell Stock with Cooldown
- Leetcode Best Time to Buy and Sell Stock with Cooldown
- LeetCode:Best Time to Buy and Sell Stock with Cooldown
- LeetCode--Best Time to Buy and Sell Stock with Cooldown
- [LeetCode] [Python] [DP] Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock III Leetcode Python
- [leetcode: Python] 121. Best Time to Buy and Sell Stock
- Leetcode-Best Time to Buy and Sell Stock-Python
- 【LeetCode with Python】 Best Time to Buy and Sell Stock II
- 基于卷积神经网络的手写汉字识别[matlab版本][可识别509类汉字]
- Android 如何判断拨打电话对方是否接听
- opencv3.x+opencv_contrib安装
- MyBatis_4
- SSH使用QBC查询时无法将查处的集合存入实体集合中,而是返回Object[]
- 【LeetCode with Python】 Best Time to Buy and Sell Stockd
- Spring json和 Map, List等bean的转换
- Java的的方法重载和方法重写
- 好用的百度翻译
- 野指针
- Elevator HDU
- 2017 浙江省赛
- 多个线程之间共享数据的方式
- Android Intent总结