买股票题目一种很好的通用解法
2017-02-24 16:54
225 查看
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/?tab=Description
题目是最多两次,但是下面的解法非常好,也能够覆盖仅仅一次的情况。
https://discuss.leetcode.com/topic/5934/is-it-best-solution-with-o-n-o-1/2
代码很简短,思路也非常好:
但是上面对于最多N次这种更加通用的形式,就不太好用了。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/?tab=Description
上面对于最多买n次类型的题目,要用到DP才行。
解法看这里:
https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java
其实含义也很明确:
tmpMax是当前时间状态持股之后的最大收益(很可能是负的)
t[i][j]是记录的实际收益。
题目是最多两次,但是下面的解法非常好,也能够覆盖仅仅一次的情况。
https://discuss.leetcode.com/topic/5934/is-it-best-solution-with-o-n-o-1/2
代码很简短,思路也非常好:
public class Solution { public int maxProfit(int[] prices) { int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE; int release1 = 0, release2 = 0; for(int i:prices){ // Assume we only have 0 money at first release2 = Math.max(release2, hold2+i); // The maximum if we've just sold 2nd stock so far. hold2 = Math.max(hold2, release1-i); // The maximum if we've just buy 2nd stock so far. release1 = Math.max(release1, hold1+i); // The maximum if we've just sold 1nd stock so far. hold1 = Math.max(hold1, -i); // The maximum if we've just buy 1st stock so far. } return release2; ///Since release1 is initiated as 0, so release2 will always higher than release1. } }
但是上面对于最多N次这种更加通用的形式,就不太好用了。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/?tab=Description
上面对于最多买n次类型的题目,要用到DP才行。
解法看这里:
https://discuss.leetcode.com/topic/8984/a-concise-dp-solution-in-java
其实含义也很明确:
tmpMax是当前时间状态持股之后的最大收益(很可能是负的)
t[i][j]是记录的实际收益。
public int maxProfit(int k, int[] prices) { int len = prices.length; if (k >= len / 2) return quickSolve(prices); int[][] t = new int[k + 1][len]; for (int i = 1; i <= k; i++) { int tmpMax = -prices[0]; for (int j = 1; j < len; j++) { t[i][j] = Math.max(t[i][j - 1], prices[j] + tmpMax); tmpMax = Math.max(tmpMax, t[i - 1][j - 1] - prices[j]); } } return t[k][len - 1]; } private int quickSolve(int[] prices) { int len = prices.length, profit = 0; for (int i = 1; i < len; i++) // as long as there is a price gap, we gain a profit. if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; return profit; }
相关文章推荐
- LeetCode Swap Nodes in Pairs题目的一种简洁解法
- 一个小题目的三种不同的解法
- nyoj 题目8 一种排序
- 游戏中的一种通用提示框(1)
- bzoj1007: [HNOI2008]水平可见直线 关于一类半半平面交题目的解法研究
- 常用木马病毒的通用解法
- Android 一种通用的按键精灵的实现思路
- 浙江大学ACM2060题目原代码 (四种解法)
- POJ 1088滑雪的一种非记忆搜索的解法
- 一种优化Kettle转换性能的通用方法
- 一种java对象转换成protobuf对象通用方法
- 高手详解 木马和病毒清除的通用解法
- 面试题目别有洞天 -> 从es6优雅解法,到降级polyfill,再到redux reducer迷之命名
- 2017校招全国统一模拟考试(第五场)JavaScript解法记录(题目来源-->牛客网)
- FizzBuzz的一种解法
- 微软201604笔试题目3 Demo Day 动态规划解法
- 对找数的一种解法
- 将m,n(m>n)的连续自然数序列,打乱顺序重新排列,随机取出一个数,试问取出的这个数是多少?使用一种解法,时间复杂度O(m-n),空间复杂度O(1)
- 华为机试题目--2011-9-14 10:30--11:30(另外解法)
- 打表找规律猜想是一种很好用的刷题技巧,写短码有用