题目如下
话不多直接上代码
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let profit = 0; // 初始利润设为0
let min = prices[0]; // 确定一个股票中的最小值
for (let i = 1; i < prices.length; i++) {
if (prices[i] < min) {
// 遍历时进行最小值赋值
min = prices[i];
} else if (prices[i] - min > profit) {
// 如果出现比最大利润还要大的就进行重新赋值
profit = prices[i] - min;
}
}
return profit;
};
主要思路就是遍历一下股票数组,找到最小值,如果出现比最大利润还要大的就重新赋值,这个方法比较易于理解。