@@ -1176,40 +1176,5 @@ let nums = [8,4,2,8,4];
11761176// console.log(specialTriplets(nums));
11771177
11781178
1179- /**
1180- * 3573. Best Time to Buy and Sell Stock V
1181- *
1182- * 正常交易:i天買,j天賣(i < j),利潤:proces[j] - prices[i]
1183- * 炒短線:i天賣,j天買回來(i < j),利潤:prices[i] - prices[j]
1184- * 不能同一天買賣單張股票
1185- * 回傳在交易k次後最多能賺多少
1186- *
1187- * @param {number[] } prices 第i天的股價
1188- * @param {number } k 最多只能交易k次
1189- * @return {number }
1190- */
1191- var maximumProfit = function ( prices , k ) {
1192- const firstPrice = prices [ 0 ] ;
1193- const dp = Array ( k + 1 ) . fill ( null ) . map ( ( ) => ( {
1194- maxProfit : 0 ,
1195- buyHold : - firstPrice ,
1196- sellHold : firstPrice
1197- } ) ) ;
1198- for ( let i = 0 ; i < prices . length ; ++ i ) {
1199- const current = prices [ i ] ;
1200- for ( let j = k ; j > 0 ; -- j ) {
1201- const prevProfit = dp [ j - 1 ] . maxProfit ;
1202- dp [ j ] . maxProfit = Math . max ( dp [ j ] . maxProfit , dp [ j ] . buyHold + current , dp [ j ] . sellHold - current ) ;
1203- dp [ j ] . buyHold = Math . max ( dp [ j ] . buyHold , prevProfit - current ) ;
1204- dp [ j ] . sellHold = Math . max ( dp [ j ] . sellHold , prevProfit + current ) ;
1205- }
1206- }
1207- return dp [ k ] . maxProfit ;
1208- } ;
1209- let prices = [ 1 , 7 , 9 , 8 , 2 ] , k = 2 ;
1210- // 14
1211- // can make $14 of profit through 2 transactions:
1212- // A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.
1213- // A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.
1214- // 9 - 1 = 8 ; 8 - 2 = 6; 8 + 6 = 14
1215- console . log ( maximumProfit ( prices , k ) )
1179+
1180+
0 commit comments