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 1a75abd

Browse files
Merge pull request youngyangyang04#2126 from Lozakaka/patch-18
提供JAVA的2*2數組版本
2 parents 8bd216b + 4fab08d commit 1a75abd

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

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

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,8 +243,27 @@ class Solution {
243243
}
244244
}
245245
```
246+
> 动态规划:版本二(使用二維數組(和卡哥思路一致),下面還有使用一維滾動數組的更優化版本)
246247

247-
> 动态规划:版本二
248+
```Java
249+
class Solution {
250+
public int maxProfit(int[] prices) {
251+
int len = prices.length;
252+
int dp[][] = new int[2][2];
253+
254+
dp[0][0] = - prices[0];
255+
dp[0][1] = 0;
256+
257+
for (int i = 1; i < len; i++){
258+
dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], - prices[i]);
259+
dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], prices[i] + dp[(i - 1) % 2][0]);
260+
}
261+
return dp[(len - 1) % 2][1];
262+
}
263+
}
264+
```
265+
266+
> 动态规划:版本二(使用一維數組)
248267

249268
``` java
250269
class Solution {
@@ -271,6 +290,10 @@ class Solution {
271290
}
272291
}
273292
```
293+
```Java
294+
295+
```
296+
274297

275298
Python:
276299

0 commit comments

Comments
(0)

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