日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode--188. 买卖股票的最佳时机Ⅳ

發(fā)布時(shí)間:2024/7/19 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode--188. 买卖股票的最佳时机Ⅳ 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

給定一個(gè)數(shù)組,它的第 i 個(gè)元素是一支給定的股票在第 i 天的價(jià)格。

設(shè)計(jì)一個(gè)算法來計(jì)算你所能獲取的最大利潤(rùn)。你最多可以完成 k 筆交易。

注意:?你不能同時(shí)參與多筆交易(你必須在再次購(gòu)買前出售掉之前的股票)。

示例?1:

輸入: [2,4,1], k = 2
輸出: 2
解釋: 在第 1 天 (股票價(jià)格 = 2) 的時(shí)候買入,在第 2 天 (股票價(jià)格 = 4) 的時(shí)候賣出,這筆交易所能獲得利潤(rùn) = 4-2 = 2 。
示例 2:

輸入: [3,2,6,5,0,3], k = 2
輸出: 7
解釋: 在第 2 天 (股票價(jià)格 = 2) 的時(shí)候買入,在第 3 天 (股票價(jià)格 = 6) 的時(shí)候賣出, 這筆交易所能獲得利潤(rùn) = 6-2 = 4 。
?? ? 隨后,在第 5 天 (股票價(jià)格 = 0) 的時(shí)候買入,在第 6 天 (股票價(jià)格 = 3) 的時(shí)候賣出, 這筆交易所能獲得利潤(rùn) = 3-0 = 3 。

思路:同之前的允許交易兩次的題類似,只不過把交易次數(shù)k變大

但需要注意,這道題定義dp[length][k][2],會(huì)超出內(nèi)存限制,所有應(yīng)該是k過大,k最大不過是數(shù)組的一半,他的交易數(shù)量不可能超過這個(gè)值,所以當(dāng)交易次數(shù)超過數(shù)組長(zhǎng)度一半時(shí),調(diào)用之前的方法maxProfit1,k視為無限大,可以忽略,定義dp[length][2]

之前交易兩次的鏈接:https://mp.csdn.net/postedit/102924843

提交的代碼:

class Solution {
? ? public static int maxProfit1(int[] prices) {
?? ?int sum=0;
? ? ? ? for(int i=1;i<prices.length;i++)
? ? ? ? {
? ? ? ? ?? ?if(prices[i]-prices[i-1]>0)
? ? ? ? ?? ?{
? ? ? ? ?? ??? ?sum+=prices[i]-prices[i-1];
? ? ? ? ?? ?}
? ? ? ? }
? ? ? ? return sum;
? ? }
? ? public int maxProfit(int k, int[] prices) {
? ? ? ? if(k>prices.length/2)
? ? ? ? {
? ? ? ? ? ? return maxProfit1(prices);
? ? ? ? }
? ? ? ? if(prices.length==0||k==0)
? ? {
? ? ? ? return 0;
? ? }
?? ?int dp[][][] = new int[prices.length][k+1][2];
?? ?dp[0][0][0] = 0;
? ? dp[0][0][1] = Integer.MIN_VALUE >> 1;
? ? for(int i=1;i<=k;i++)
? ? {
? ? ?? ?dp[0][i][0]=0;
? ? ?? ?dp[0][i][1]=-prices[0];
? ? }
?? ?dp[0][1][1] = -prices[0];
?? ?for(int i=1;i<prices.length;i++)
?? ?{
?? ??? ?for(int j = 1;j<=k;j++)
?? ??? ?{
?? ??? ??? ?dp[i][j][0]=Math.max(dp[i-1][j][0],dp[i-1][j][1]+prices[i]);
?? ??? ??? ?dp[i][j][1]=Math.max(dp[i-1][j][1],dp[i-1][j-1][0]-prices[i]);?? ?
?? ??? ?}
?? ?}
?? ?int max = dp[prices.length-1][0][0];
?? ?for(int i=1;i<=k;i++)
?? ?{
?? ??? ?if(dp[prices.length-1][k][0]>max)
?? ??? ?{
?? ??? ??? ?max = dp[prices.length-1][k][0];
?? ??? ?}
?? ?}
?? ?return max;

? ? }
}

總結(jié)

以上是生活随笔為你收集整理的Leetcode--188. 买卖股票的最佳时机Ⅳ的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。