数组 - 买卖股票的最佳时机

题目

https://leetcode-cn.com/explore/featured/card/top-interview-questions-easy/1/array/22/

个人解法

测试用例数(个) 执行用时(ms) 战胜
201 1820 1.12%
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    var len = prices.length;
    var maxProfit = 0;

    for (var i = 0 ; i < len ; i++) {
        var index = i;
        var j = i;
        var totalProfit = 0;
        var tProfit = -1;

        while (j < len) {
            j++;

            if (prices[j] !== undefined) {
                var priceDuration = prices[j] - prices[index];

                if (priceDuration > tProfit) {
                    tProfit = priceDuration;
                } else  {
                    totalProfit += tProfit;
                    tProfit = 0;
                    index = j;
                }
            } else {
                totalProfit += tProfit;
                tProfit = 0;
            }
        }

        if (totalProfit > maxProfit) {
            maxProfit = totalProfit;
        }
    }

    return maxProfit;
};

最快解法

测试用例数(个) 执行用时(ms) 战胜
161 56 100%
/**
 * @param {number[]} prices
 * @return {number}
 */
let maxProfit = function(prices) {
    let max = 0;
    for (let i = 1; i < prices.length; i++) {
        if (prices[i] - prices[i - 1] > 0) {
            max += prices[i] - prices[i - 1];
        }
    }
    return max;
}

分析

这个性能差距还是很大的,个人解决还是有些绕。

个人解法:

是当收益总和下降时,卖掉股票。

最快解法:

只要当第二天的股价低于前一天,卖掉股票。
*****
Written by Zheng Yu on 25 March 2019