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 391a04b

Browse files
Merge pull request youngyangyang04#623 from DoubleYellowIce/master
添加 买卖股票的最佳时机 IV java版本一维空间优化代码
2 parents c29210e + 1cc94d4 commit 391a04b

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

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

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ class Solution {
196196
}
197197
}
198198

199-
// 版本二: 空间优化
199+
// 版本二: 二维 dp数组
200200
class Solution {
201201
public int maxProfit(int k, int[] prices) {
202202
if (prices.length == 0) return 0;
@@ -220,6 +220,25 @@ class Solution {
220220
return dp[len - 1][k*2];
221221
}
222222
}
223+
224+
//版本三:一维 dp数组
225+
class Solution {
226+
public int maxProfit(int k, int[] prices) {
227+
//在版本二的基础上,由于我们只关心前一天的股票买入情况,所以只存储前一天的股票买入情况
228+
if(prices.length==0)return 0;
229+
int[] dp=new int[2*k+1];
230+
for (int i = 1; i <2*k ; i+=2) {
231+
dp[i]=-prices[0];
232+
}
233+
for (int i = 0; i <prices.length ; i++) {
234+
for (int j = 1; j <2*k ; j+=2) {
235+
dp[j]=Math.max(dp[j],dp[j-1]-prices[i]);
236+
dp[j+1]=Math.max(dp[j+1],dp[j]+prices[i]);
237+
}
238+
}
239+
return dp[2*k];
240+
}
241+
}
223242
```
224243

225244

0 commit comments

Comments
(0)

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