123 Best Time to Buy and Sell Stock III
2016-02-03 16:20
309 查看
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/
题目:
解题思路:
这题的考点是动态规划。
这题是 188 Best Time to Buy and Sell Stock IV 这题的特殊情况。即 k = 2 时。
代码实现:
题目:
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).
解题思路:
这题的考点是动态规划。
这题是 188 Best Time to Buy and Sell Stock IV 这题的特殊情况。即 k = 2 时。
代码实现:
public class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length == 0) return 0; int[] local = new int[3]; int[] global = new int[3]; for(int i = 1; i < prices.length; i ++) { int diff = prices[i] - prices[i - 1]; for(int j = 2; j >= 1; j --) { local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff); global[j] = Math.max(global[j], local[j]); } } return global[2]; } }
198 / 198 test cases passed. Status: Accepted Runtime: 9 ms
相关文章推荐
- 大话设计模式——六大原则
- utf-8的问题
- SharePoint Tricks - Survey
- Hibernate JPA实体继承的映射(二) @MappedSuperclass
- Comparison method violates its general contract
- java邮件解析3
- 看图识“字”(6)-关键词频率越高面积越大
- Linux atexit函数解析
- git - 简明指南--很酷的git网址【转】
- excel的if函数
- BloomFilter算法概述
- Windows 10 UWP/Windows 10 Mobile GIF图片显示
- Spring MVC 教程,快速入门,深入分析
- RDLC报表:每页显示N条记录
- C++ AMP同CUDA之间的性能比较
- java邮件解析2
- 看图识“字”(5)-饼分图使数据变为面积
- ExpandableTextView可下拉扩展的TextView
- 性能测试过程中部分指标关联
- eclipse 使用 git@osc