题干
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
思路一:暴力(超时)
循环遍历加判断
let profit = 0;
let length = prices.length
for (let index = 0; index < length; index++) {
let beginDay = prices[index]
for (let indey = index + 1; indey < length; indey++) {
let tempprofit = prices[indey] - beginDay
if (tempprofit > profit) {
profit = tempprofit
}
}
}
return profit
思路二:贪心
我们设定一个最小价格和一个当前利润,然后循环一次,遇到比当前最小价格小的值,替换最小价格。如果当前循环中的利润大于当前利润,替换当前利润,这样就可以找到最小的投入点,并可以计算出最高抛出点
执行用时:124 ms, 在所有 JavaScript 提交中击败了38.04%的用户
内存消耗:47.6 MB, 在所有 JavaScript 提交中击败了66.07%的用户
var maxProfit = function (prices) {
let minprice = prices[0];
let profit = 0;
for (let i = 0; i < prices.length; i++) {
if (minprice > prices[i]) {
minprice = prices[i]
} else if (prices[i] - minprice > profit) {
profit = prices[i] - minprice
}
}
return profit