动态规划-188. Best Time to Buy and Sell Stock IV
来源:互联网 发布:阿里云解析新网域名 编辑:程序博客网 时间:2024/06/05 06:52
题目
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 k transactions.
题意解读:你有一个数组,第i个元素就是第i天的股票价格。你可以进行最多k次操作
/** * dp[i, j] represents the max profit up until prices[j] using at most i transactions. * dp[i, j] = max(dp[i, j-1], prices[j] - prices[jj] + dp[i-1, jj]) { jj in range of [0, j-1] } * = max(dp[i, j-1], prices[j] + max(dp[i-1, jj] - prices[jj])) *dp[i,j] = dp[i,j-1]表示第在第j天不做任何的交易 *dp[i][j] = max(prices[j] - prices[jj] + dp[i-1, jj] { jj in range of [0, j-1] }) 表示第jj天买进股票,第j天卖出股票。完成第i次交易 * dp[0, j] = 0; 0 transactions makes 0 profit * dp[i, 0] = 0; if there is only one price data point you can't make any transaction. */class Solution { public int maxProfit(int k, int[] prices) { if(prices.length == 0) return 0; int n = prices.length; //分为两种情况,当k>=n/2时,可以进行最大次数的交易。就是随便买,随便卖 if(k >= n/2){ int maxPro = 0; for(int i = 1; i < n; i++) maxPro += (prices[i]>prices[i-1] ?prices[i]-prices[i-1]:0); return maxPro; } //第二种情况 int[][] dp = new int[k+1][n]; for(int i = 1; i <= k; i++ ){ int localMax = dp[i-1][0] - prices[0]; for(int j = 1; j < n; j++){ dp[i][j] = Math.max(dp[i][j-1],prices[j]+localMax); localMax = Math.max(localMax,dp[i-1][j]-prices[j]); } } return dp[k][n-1]; }}
阅读全文
0 0
- 【动态规划】Best Time to Buy and Sell Stock IV
- Best Time to Buy and Sell Stock IV(动态规划)
- 动态规划-188. Best Time to Buy and Sell Stock IV
- Leetcode(W9):188. Best Time to Buy and Sell Stock IV(动态规划)
- 【LeetCode】Best Time to Buy and Sell Stock IV 动态规划dp解法(C++)
- LeetCode 188 Best Time to Buy and Sell Stock IV (动态规划 推荐)
- Best Time to Buy and Sell Stock I II III 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
- 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】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
- WebSocket+多线程python socket网页版实时在线聊天实现
- JVM的简单实现
- Air Raid HDU
- [VCS-git]-01.git安装及常用客户端命令
- 二维码
- 动态规划-188. Best Time to Buy and Sell Stock IV
- bzoj 4936: [Ceoi2016]match
- stm32f103 spi slave从机模式miso需要上拉
- Recover the Smallest Number (30)
- 使用ViewPager实现屏幕滑动
- lambda表达式杂谈
- leetcode 372. Super Pow 快速幂实现
- String类型转化成Int类型
- 关于用户 root密码忘记时的密码重制