https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
// let max = 0
// for (let i = 0; i < prices.length - 1; i++) {
// for (let j = i + 1; j < prices.length; j++) {
// max = Math.max(max, prices[j] - prices[i])
// }
// }
// return max

let minPrice = prices[0]
let maxProfit = 0
for (let i = 1; i < prices.length; i++) {
// if (prices[i] < minPrice) {
// minPrice = prices[i]
// } else {
// maxProfit = Math.max(prices[i] - minPrice, maxProfit)
// }
minPrice = Math.min(prices[i], minPrice)
maxProfit = Math.max(prices[i] - minPrice, maxProfit)
}
return maxProfit
};