Leetcode: Best Time to Buy and Sell Stock III
2015-09-12 14:22
411 查看
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’[code]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
相关文章推荐
- 二叉查找树
- 浅析mysql 共享表空间与独享表空间以及他们之间的转化
- jQuery 完成ajax传jsonObject数据,并在后台处理
- Java学习之ThreadLocal
- swun 1397 来电显示
- java中boolean与字符串或者数字1和0的转换
- Linux简介
- The connection to adb is down和no configs match configspec错误
- gettimeofday
- Android 4.4 Kitkat Phone工作流程浅析(八)__Phone状态分析
- Ztree之复选框功能(三)
- Linux目录
- linux c 检测网络状态
- hdoj 2404 Permutation Recovery 【水题(规律)】
- 堆和栈的区别
- Android基础之json数据的几种解析方法
- IOS开发者常用的10个Xcode插件
- HttpRequest信息内容介绍
- php后管理分类导航菜单
- Android 4.4 Kitkat Phone工作流程浅析(九)__状态通知流程分析