心得
题解
- 可以用动规通过i天是否持只依赖前一天状态来判断,通过当前是否持有,持有卖出通过前一状态递推
// 贪心,时间复杂度O(n),空间O(1)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int minPrice = INT_MAX
int result = 0
for (int i = 0
minPrice = min(minPrice, prices[i])
result = max(prices[i] - minPrice, result)
}
return result
}
}
// 动规思路 时间O(N)空间(N)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int length = prices.size()
if (length == 0) return 0
vector<vector<int>> dp(length, vector<int>(2))
dp[0][0] -= prices[0]
dp[0][1] = 0
for (int i = 1
dp[i][0] = max(dp[i - 1][0], -prices[i])
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
}
return dp[length - 1][1]
}
}
// 动规优化空间,只取决前一状态,可以将空间复杂度压缩N到1
class Solution {
public:
int maxProfit(vector<int>& prices) {
int length = prices.size()
if (length == 0) return 0
vector<vector<int>> dp(2, vector<int>(2))
dp[0][0] -= prices[0]
dp[0][1] = 0
for (int i = 1
dp[i % 2][0] = max(dp[(i - 1) % 2][0], -prices[i])
dp[i % 2][1] = max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i])
}
return dp[(length - 1) % 2][1]
}
}
心得
- 基本同前一天,唯一区别在于第i天持有的买入情况即
dp[i][0]递推式不一样,此时可以多次买入卖出
题解
// 动规思路 时间O(N)空间(N)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int length = prices.size()
if (length == 0) return 0
vector<vector<int>> dp(length, vector<int>(2))
dp[0][0] -= prices[0]
dp[0][1] = 0
for (int i = 1
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] - prices[i])
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i])
}
return dp[length - 1][1]
}
}
// 动规优化空间,只取决前一状态,可以将空间复杂度压缩N到1
class Solution {
public:
int maxProfit(vector<int>& prices) {
int length = prices.size()
if (length == 0) return 0
vector<vector<int>> dp(2, vector<int>(2))
dp[0][0] -= prices[0]
dp[0][1] = 0
for (int i = 1
dp[i % 2][0] = max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] - prices[i])
dp[i % 2][1] = max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i])
}
return dp[(length - 1) % 2][1]
}
}