Leetcode: Best Time to Buy and Sell Stock III
来源:互联网 发布:什么是淘宝团队 编辑:程序博客网 时间:2024/06/15 20:15
Question
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 at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Hide Tags Array Dynamic Programming
Hide Similar Problems (M) Best Time to Buy and Sell Stock (M) Best Time to Buy and Sell Stock II (H) Best Time to Buy and Sell Stock IV
Solution
see ‘Best Time to Buy and Sell Stock IV’
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if prices==[]: return 0 if 2>=len(prices): return self.maxprofit2(prices) globalv = [0]*3 localv = [0]*3 for i in range(1,len(prices)): diff = prices[i] - prices[i-1] for j in range(2,0,-1): localv[j] = max( globalv[j-1] + max(diff,0), localv[j]+diff ) globalv[j] = max( globalv[j], localv[j] ) return globalv[2] def maxprofit2(self, prices): maxv = 0 for ind in range(1,len(prices)): if prices[ind]>prices[ind-1]: maxv += prices[ind] - prices[ind-1] return maxv
0 0
- LeetCode Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- leetcode 62: Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- 【leetcode】Best Time to Buy and Sell Stock III
- LeetCode - Best Time to Buy and Sell Stock III
- LeetCode之Best Time to Buy and Sell Stock III
- [LeetCode]Best Time to Buy and Sell Stock III
- LeetCode: Best Time to Buy and Sell Stock III
- [Leetcode]Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III
- leetcode题目:Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock III
- LeetCode-Best Time to Buy and Sell Stock III
- 最大子列和问题
- 二叉查找树
- Linux简介
- Sublime Text 2/3破解方法及注册码
- Android 4.4 Kitkat Phone工作流程浅析(七)__来电(MT)响铃流程
- Leetcode: Best Time to Buy and Sell Stock III
- centOS安装JDK
- Android 4.4 Kitkat Phone工作流程浅析(六)__InCallActivity显示更新流程
- hdu 4747 Pet
- Android 4.4 Kitkat Phone工作流程浅析(五)__MT(来电)流程分析
- 查看Linux系统版本信息方法
- HDU 1503 Advanced Fruits(LCS+输出路径)
- 解决ORA-27154,ORA-27300,ORA-27301:No space left on device
- mongodb学习一 关于 下载 安装 以及增删改查 还有一些简单的命令