Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b1e8b17

Browse files
新增java一維數組解法(很卡哥邏輯一致)
原本的那個版本不知道在寫什麼
1 parent ec6c3e9 commit b1e8b17

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

‎problems/0188.买卖股票的最佳时机IV.md‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ class Solution {
227227
}
228228
}
229229

230-
//版本三:一维 dp数组
230+
//版本三:一维 dp数组 (下面有和卡哥邏輯一致的一維數組JAVA解法)
231231
class Solution {
232232
public int maxProfit(int k, int[] prices) {
233233
if(prices.length == 0){
@@ -259,6 +259,41 @@ class Solution {
259259
}
260260
}
261261
```
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+
```
262297

263298
Python:
264299

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /