Open FE92star opened 3 years ago
/**
* @param {number[]} prices
* @param {number} fee
* @return {number}
*/
var maxProfit = function(prices, fee) {
const n = prices.length
let buy = prices[0] + fee // 购入价格
let money = 0 // 利润
for(let i = 1;i < n; i++) {
// 股价加上手续费低于购入价,则选择当前更低的股价购入
// 如果股价高于购入价,则卖出获得利润,并且重新买入新的股票
if(prices[i] + fee < buy) {
buy = prices[i] + fee
} else if(prices[i] > buy) {
money += prices[i] - buy
buy = prices[i]
}
}
return money
};
/**
* @param {number[]} prices
* @param {number} fee
* @return {number}
*/
var maxProfit = function(prices, fee) {
let min = prices[0], r = 0, i = 0, t
while(++i < prices.length) {
if (prices[i] < min) {
min = prices[i]
} else if ((t = prices[i] - min - fee) > 0) {
r += t
min = prices[i] - fee
}
}
return r
}
买卖股票的最佳时机含手续费