题目1:只进行一笔交易 力扣
思路: 变量low表示当天前的最低点、res表示当天或者是当天之前交易能获得的最大利润, 每一天更新一次low和res
代码:
var maxProfit = function(prices) {
let low = prices[0]
let res = 0
for (let i = 1; i < prices.length; i ++) {
low = Math.min(low, prices[i])
res = Math.max(res, prices[i] - low)
}
return res
};
结果:
题目2:交易次数不限 力扣
思路:既然交易次数不限且可以当天卖出当天买入,那就只要能赚钱都去做这笔交易,就是说只要涨价,涨的价你都能赚到,把涨的价累加就可以了。
代码:
var maxProfit = function(prices) {
let res = 0
for (let i = 1; i < prices.length; i ++) {
if (prices[i] > prices[i - 1]) {
res += prices[i] - prices[i - 1]
}
}
return res
};
结果: