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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

Leetcode--123. 买卖股票的最佳时间Ⅲ

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

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

設(shè)計一個算法來計算你所能獲取的最大利潤。你最多可以完成?兩筆?交易。

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

示例?1:

輸入: [3,3,5,0,0,3,1,4]
輸出: 6
解釋: 在第 4 天(股票價格 = 0)的時候買入,在第 6 天(股票價格 = 3)的時候賣出,這筆交易所能獲得利潤 = 3-0 = 3 。
?? ? 隨后,在第 7 天(股票價格 = 1)的時候買入,在第 8 天 (股票價格 = 4)的時候賣出,這筆交易所能獲得利潤 = 4-1 = 3 。
示例 2:

輸入: [1,2,3,4,5]
輸出: 4
解釋: 在第 1 天(股票價格 = 1)的時候買入,在第 5 天 (股票價格 = 5)的時候賣出, 這筆交易所能獲得利潤 = 5-1 = 4 。 ??
?? ? 注意你不能在第 1 天和第 2 天接連購買股票,之后再將它們賣出。 ??
?? ? 因為這樣屬于同時參與了多筆交易,你必須在再次購買前出售掉之前的股票。
示例 3:

輸入: [7,6,4,3,1]?
輸出: 0?
解釋: 在這個情況下, 沒有交易完成, 所以最大利潤為 0。

思路:這道題與之前的股票題略有不同,原因在于在最后一天需要把不持股情況下的所有交易次數(shù)的收益作比較取最大值

之前的股票題:https://mp.csdn.net/postedit/102913586

提交的代碼:

class Solution {
? ? public int maxProfit(int[] prices) {
? ? ? if(prices.length==0)
? ? {
? ? ? ? return 0;
? ? }
?? ?int dp[][][] = new int[prices.length][3][2];//第二維0表示未交易,1表示1次,2表示兩次
?? ?dp[0][0][0] = 0;
?? ?dp[0][1][1] = -prices[0];
?? ?dp[0][1][0] = Integer.MIN_VALUE >> 1;
? ? dp[0][2][0] = Integer.MIN_VALUE >> 1;
? ? dp[0][2][1] = Integer.MIN_VALUE >> 1;
? ? dp[0][0][1] = Integer.MIN_VALUE >> 1;
?? ?for(int i=1;i<prices.length;i++)
?? ?{
?? ??? ?for(int j = 1;j<=2;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]);?? ?
?? ??? ?}
?? ?}
?? ?return Math.max(dp[prices.length-1][2][0],Math.max( dp[prices.length-1][0][0],dp[prices.length-1][1][0]));
? ? }
}

完整的代碼:


public class Solution123 {
public static int maxProfit(int[] prices) {
?? ?if(prices.length==0)
? ? {
? ? ? ? return 0;
? ? }
?? ?int dp[][][] = new int[prices.length][3][2];//第二維0表示未交易,1表示1次,2表示兩次
?? ?dp[0][0][0] = 0;
?? ?dp[0][1][1] = -prices[0];
?? ?dp[0][1][0] = Integer.MIN_VALUE >> 1;
? ? dp[0][2][0] = Integer.MIN_VALUE >> 1;
? ? dp[0][2][1] = Integer.MIN_VALUE >> 1;
? ? dp[0][0][1] = Integer.MIN_VALUE >> 1;
?? ?for(int i=1;i<prices.length;i++)
?? ?{
?? ??? ?for(int j = 1;j<=2;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]);?? ?
?? ??? ?}
?? ?}
?? ?return Math.max(dp[prices.length-1][2][0],Math.max( dp[prices.length-1][0][0],dp[prices.length-1][1][0]));
? ? }

public static void main(String[] args)
{
?? ?//int nums[] = {3,3,5,0,0,3,1,4};
?? ?int nums[] = {1,2,3,4,5};
?? ?System.out.println(maxProfit(nums));
}
}
?

總結(jié)

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

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