Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

第311题(2020-09-24):假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少? #314

Open
qappleh opened this issue Sep 24, 2020 · 1 comment

Comments

@qappleh
Copy link
Owner

qappleh commented Sep 24, 2020

例如:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。

@qappleh
Copy link
Owner Author

qappleh commented Oct 13, 2020

代码

/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    //此问题的实质就是找到两个差值最大的数,前提是小的在前,大的在后
    //要把此问题的时间复杂度控制在O(n-1)并不难
    let profits = 0;
    let min = prices[0];
    const len = prices.length;
    for(let i = 1; i < len; i ++) {
        min = Math.min(min, prices[i]);
        profits = Math.max(profits, prices[i] - min);
    }
    return profits;
};

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant