mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 16:54:50 +08:00
格式化了123一维数组空间优化的java代码,并更正了注释
This commit is contained in:
@ -221,23 +221,23 @@ class Solution {
|
|||||||
// 版本二: 空间优化
|
// 版本二: 空间优化
|
||||||
class Solution {
|
class Solution {
|
||||||
public int maxProfit(int[] prices) {
|
public int maxProfit(int[] prices) {
|
||||||
int[] dp=new int[4];
|
int[] dp = new int[4];
|
||||||
// 存储两天的状态就行了
|
// 存储两次交易的状态就行了
|
||||||
// dp[0]代表第一次买入
|
// dp[0]代表第一次交易的买入
|
||||||
dp[0]=-prices[0];
|
dp[0] = -prices[0];
|
||||||
// dp[1]代表第一次卖出
|
// dp[1]代表第一次交易的卖出
|
||||||
dp[1]=0;
|
dp[1] = 0;
|
||||||
// dp[2]代表第二次买入
|
// dp[2]代表第二次交易的买入
|
||||||
dp[2]=-prices[0];
|
dp[2] = -prices[0];
|
||||||
// dp[3]代表第二次卖出
|
// dp[3]代表第二次交易的卖出
|
||||||
dp[3]=0;
|
dp[3] = 0;
|
||||||
for(int i=1; i<=prices.length; i++){
|
for(int i = 1; i <= prices.length; i++){
|
||||||
// 要么保持不变,要么没有就买,有了就卖
|
// 要么保持不变,要么没有就买,有了就卖
|
||||||
dp[0]=Math.max(dp[0], -prices[i-1]);
|
dp[0] = Math.max(dp[0], -prices[i-1]);
|
||||||
dp[1]=Math.max(dp[1], dp[0]+prices[i-1]);
|
dp[1] = Math.max(dp[1], dp[0]+prices[i-1]);
|
||||||
// 这已经是第二天了,所以得加上前一天卖出去的价格
|
// 这已经是第二次交易了,所以得加上前一次交易卖出去的收获
|
||||||
dp[2]=Math.max(dp[2], dp[1]-prices[i-1]);
|
dp[2] = Math.max(dp[2], dp[1]-prices[i-1]);
|
||||||
dp[3]=Math.max(dp[3], dp[2]+prices[i-1]);
|
dp[3] = Math.max(dp[3], dp[2]+ prices[i-1]);
|
||||||
}
|
}
|
||||||
return dp[3];
|
return dp[3];
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user