LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
来源:互联网 发布:2016网络情歌对唱大全 编辑:程序博客网 时间:2024/06/05 09:12
Say you have an array for which the ith element is the price of a given stock on dayi.
Design an algorithm to find the maximum profit. You may complete at mostk transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/
题目分析:股票系列最后一题,最多买k次,对于两次的时候有这样一种很好理解的解法:
for (int price : prices) { buy1 = Math.max(buy1, -price); sell1 = Math.max(sell1, buy1 + price); buy2 = Math.max(buy2, sell1 - price); sell2 = Math.max(sell2, buy2 + price);}然后推广的k次,实际上就是加一层循环,有一个优化,如果k >= n / 2,相当于可以买无限次,直接用无限次的做法On扫一下即可
public class Solution { public int maxProfit(int k, int[] prices) { int n = prices.length; if (n < 2) { return 0; } if (k >= n / 2) { int ans = 0; for (int i = 0; i < n - 1; i ++) { if (prices[i + 1] > prices[i]) { ans += prices[i + 1] - prices[i]; } } return ans; } else { int[] sell = new int[n + 1]; int[] buy = new int[n + 1]; for (int i = 1; i <= n; i ++) { buy[i] = -0x3fffffff; } for (int i = 0; i < n; i ++) { for (int j = 1; j <= k; j ++) { buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]); sell[j] = Math.max(sell[j], buy[j] + prices[i]); } } return sell[k]; } }}
0 0
- LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
- 【动态规划】Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV(动态规划)
- 【LeetCode】Best Time to Buy and Sell Stock IV 动态规划dp解法(C++)
- Leetcode(W9):188. Best Time to Buy and Sell Stock IV(动态规划)
- LeetCode(188) Best Time to Buy and Sell Stock IV
- leetcode 188---Best Time to Buy and Sell Stock IV
- leetcode 188: Best Time to Buy and Sell Stock IV
- 188 Best Time to Buy and Sell Stock IV [Leetcode]
- [LeetCode 188] Best Time to Buy and Sell Stock IV
- LeetCode #188: Best Time to Buy and Sell Stock IV
- LeetCode 188 - Best Time to Buy and Sell Stock IV
- LeetCode 188 Best Time to Buy and Sell Stock IV
- Leetcode 188 Best Time to Buy and Sell Stock IV
- [LeetCode] Best Time to Buy and Sell Stock IV
- leetcode: Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV -- leetcode
- Best Time to Buy and Sell Stock IV--LeetCode
- JAVA异常处理一return
- 《懒人Shell脚本》之五——一键修改分布式系统配置文件
- Atitit 知识图谱解决方案:提供完整知识体系架构的搜索与知识结果overview
- 敏捷其实很简单(1)重读敏捷宣言
- JNI与NDK
- LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
- Android ViewPager和Fragment实现顶部导航界面滑动效果
- Mathematica关于混沌摆的简单模拟
- Open CV学习记录(五)——离群点、访问图像像素、remap、resize
- 【第九周 项目1-猴子选大王(数组版)】
- 使用MyEclipse简化Hibernate开发
- Debug与打日志的切换技巧
- Atitit 通过调用gui接口杀掉360杀毒 360卫士 qq保镖等难以结束的进程(javac# php )
- 为了督促自己学习