121.买卖股票的最佳时机
/**
* @param {number[]} prices
* @return {number}
*/
// 暴力解法,超时
var maxProfit = function (prices) {
var max = 0
// 求每天买入的最大收入
for (var i = 0; i < prices.length - 1; i++) {
for (var j = i + 1; j < prices.length; j++) {
var profit = prices[j] - prices[i]
max = Math.max(max, profit)
}
}
return max
};
var maxProfit = function (prices) {
// 只需要遍历价格数组一遍,记录历史最低点,
// 然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?
// 当考虑完所有天数之时,我们就得到了最好的答案
var minPrice = Number.MAX_VALUE
var maxprofit = 0
for (var i = 0; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i]
} else { // 当天价格高的时候才卖出
maxprofit = Math.max(prices[i] - minPrice, maxprofit)
}
}
return maxprofit
};
// 示例 1:
// 输入:[7,1,5,3,6,4]
// 输出:5
// 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
// 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
console.log(maxProfit([7, 1, 5, 3, 6, 4]))
// 示例 2:
// 输入:prices = [7,6,4,3,1]
// 输出:0
// 解释:在这种情况下, 没有交易完成, 所以最大利润为 0。
// console.log(maxProfit([7, 6, 4, 3, 1]))
// console.log(maxProfit([2, 4, 1]))
// console.log(maxProfit([3,2,6,5,0,3]));
// console.log(maxProfit([2, 1, 2, 1, 0, 1, 2]))