Cosen95 / js_algorithm

🏂js数据结构与算法 系统学习
36 stars 10 forks source link

买卖股票的最佳时机 #36

Open Cosen95 opened 4 years ago

Cosen95 commented 4 years ago

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

Cosen95 commented 4 years ago

暴力求解(两层for循环)

这道题目最简单的求解方式就是两层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
};