国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

188. Best Time to Buy and Sell Stock IV

2019-11-11 02:01:44
字體:
供稿:網(wǎng)友

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. Note: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

一刷沒ac 解題思路:dp[i][j]代表前j(索引為j)天進(jìn)行i次交易的最大利潤。假設(shè)在 j 天賣出,最大利潤dp[i][j] = Math.max(dp[i][j-1], prices[j] + tmp); tmp是上次交易(買入)剩下的利潤,tmp = Math.max(tmp, dp[i-1][j-1] - prices[j]);

public class Solution { public int maxProfit(int k, int[] prices) { //if(k < 0 || prices == null || prices.length == 0) return 0; int len = prices.length; if(k >= len/2) return uniquesolve(prices); int[][] dp = new int[k+1][len]; for(int i = 1; i <= k; i++){ int tmp = -prices[0]; for(int j = 1; j < len; j++){ dp[i][j] = Math.max(dp[i][j-1], prices[j] + tmp); tmp = Math.max(tmp, dp[i-1][j-1] - prices[j]); } } return dp[k][len-1]; } public int uniquesolve(int[] prices){ int res = 0; for(int i = 1; i < prices.length; i++){ if(prices[i] > prices[i-1]) res += prices[i] - prices[i-1]; } return res; }}
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 凌海市| 衡阳县| 涟水县| 云林县| 德安县| 丘北县| 云和县| 安多县| 天津市| 离岛区| 西贡区| 江津市| 漳平市| 交口县| 玉环县| 二连浩特市| 枣强县| 天峻县| 吉首市| 牡丹江市| 台中市| 上饶市| 襄樊市| 昭通市| 武乡县| 松原市| 太湖县| 武陟县| 定陶县| 于都县| 泗阳县| 淮安市| 乐山市| 确山县| 湟中县| 淄博市| 巴里| 丰城市| 巫山县| 海兴县| 丹东市|