//DFS TLE
var maxProfit = function (prices) {
let len = prices.length
if (len < 2) return 0
let ret = 0
//idx当前是第几天,从 0 开始
//status 0 表示不持有股票,1表示持有股票
//curProfit当前收益
const dfs = (prices, idx, status, profit) => {
if (idx >= prices.length) {
if (profit > ret) ret = profit
}
dfs(prices, idx + 1, status, profit)
if (status === 0) {
dfs(prices, idx + 1, 1, profit - prices[idx])
} else {
dfs(prices, idx + 1, 0, profit + prices[idx])
}
}
dfs(prices, 0, 0, 0)
return ret
}
//Greedy
//计算的过程并不是实际的交易过程,收益被分成了若干个阶段
var maxProfit = function (prices) {
let ret = 0
let len = prices.length
if (len < 2) return 0
for (let i = 1; i < len; i++) {
//profit += Math.max(prices[i] - prices[i - 1], 0);
// if (prices[i] > prices[i - 1]) {
// profit += prices[i] - prices[i - 1]
// }
ret += Math.max(prices[i] - prices[i - 1], 0)
}
return ret
}
//DP O(n)-O(n)
var maxProfit = function (prices) {
let len = prices.length
if (len < 2) return 0
const dp = Array.from({ length: len }, () => new Array(2))
//base case
dp[0][0] = 0
dp[0][1] = -prices[0]
for (let i = 1; i < len; i++) {
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i])
dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i])
}
return dp[len - 1][0]
}
//DP 分开定义 O(n)-O(n)
var maxProfit = function (prices) {
let len = prices.length
if (len < 2) return 0
let cash = new Array(len)
let hold = new Array(len)
cash[0] = 0
hold[0] = -prices[0]
for (let i = 1; i < len; i++) {
cash[i] = Math.max(cash[i - 1], hold[i - 1] + prices[i])
hold[i] = Math.max(hold[i - 1], cash[i - 1] - prices[i])
}
return cash[len - 1]
}
//DP O(n)-O(1)
var maxProfit = function (prices) {
let len = prices.length
if (len < 2) return 0
let dp_i_0 = 0,
dp_i_1 = -Infinity
for (let i = 0; i < len; i++) {
const temp = dp_i_0
dp_i_0 = Math.max(dp_i_0, dp_i_1 + prices[i])
dp_i_1 = Math.max(dp_i_1, temp - prices[i])
}
return dp_i_0
}