Open Cosen95 opened 4 years ago
这道题目最简单的求解方式就是两层for
循环,不断更新前后差值的最大值就好了。
/**
* @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++) {
if (prices[j] > prices[i]) {
max = Math.max(max, prices[j] - prices[i])
}
}
}
return max
};
leetcode: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/