File tree 1 file changed +36
-1
lines changed
1 file changed +36
-1
lines changed Original file line number Diff line number Diff line change @@ -227,7 +227,7 @@ class Solution {
227
227
}
228
228
}
229
229
230
- // 版本三:一维 dp数组
230
+ // 版本三:一维 dp数组 (下面有和卡哥邏輯一致的一維數組JAVA解法)
231
231
class Solution {
232
232
public int maxProfit (int k , int [] prices ) {
233
233
if (prices. length == 0 ){
@@ -259,6 +259,41 @@ class Solution {
259
259
}
260
260
}
261
261
```
262
+ ``` JAVA
263
+ class Solution {
264
+ public int maxProfit (int k , int [] prices ) {
265
+
266
+ // edge cases
267
+ if (prices. length == 0 || k == 0 )
268
+ return 0 ;
269
+
270
+
271
+ int dp[] = new int [k * 2 + 1 ];
272
+
273
+ // 和卡哥邏輯一致,奇數天購入股票,故初始化只初始化奇數天。
274
+ for (int i = 1 ; i < 2 * k + 1 ; i += 2 ){
275
+ dp[i] = - prices[0 ];
276
+ }
277
+
278
+ for (int i = 1 ; i < prices. length; i++ ){ // i 從 1 開始,因爲第 i = 0 天已經透過初始化完成了。
279
+ for (int j = 1 ; j < 2 * k + 1 ; j++ ){ // j 從 1 開始,因爲第 j = 0 天已經透過初始化完成了。
280
+ // 奇數天購買
281
+ if (j % 2 == 1 )
282
+ dp[j] = Math . max(dp[j], dp[j - 1 ] - prices[i]);
283
+ // 偶數天賣出
284
+ else
285
+ dp[j] = Math . max(dp[j], dp[j - 1 ] + prices[i]);
286
+ }
287
+ // 打印DP數組
288
+ // for(int x : dp)
289
+ // System.out.print(x +", ");
290
+ // System.out.println();
291
+ }
292
+ // return 第2 * k次賣出的獲利。
293
+ return dp[2 * k];
294
+ }
295
+ }
296
+ ```
262
297
263
298
Python:
264
299
You can’t perform that action at this time.
0 commit comments