0%

买卖股票的最佳时机

买卖股票的最佳时机

题目描述

解法一(双 loop 会超时)

1
2
3
4
5
6
7
8
9
10
11
12
13
var maxProfit = function (prices) {
let result = 0
for (let i = 0; i < prices.length; i++) {
let tempMax = 0
for (let j = i + 1; j < prices.length; j++) {
tempMax = Math.max(tempMax, prices[j])
}
let temp = tempMax - prices[i]
result = temp > 0 ? Math.max(result, temp) : result
}
return result;
};

解法二(单 loop)

1
2
3
4
5
6
7
8
9
var maxProfit = function (prices) {
let result = 0
let minValue = prices[0]
for (let i = 0; i < prices.length; i++) {
minValue = Math.min(minValue, prices[i])
result = Math.max(prices[i] - minValue, result)
}
return result;
};