美文网首页
121. Best Time to Buy and Sell S

121. Best Time to Buy and Sell S

作者: f1a94e9a1ea7 | 来源:发表于2018-12-14 11:12 被阅读10次

给一个数组,其中第 i 个元素是第 i 天的股票价格,假设只能完成一笔交易,找出最大利润。
注: 买入之前不可卖出。

  • Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: 在第二天以一块钱买进,第五天六块钱卖出是最大利润五元,输出 5 .

解析:

  1. 最简单的就是循环嵌套:
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let profit = 0;
    for(let i = 0; i < prices.length; i++) {
        let buy = prices[i]
        
        for(let j = i+1; j < prices.length; j++) {
            if(prices[i] > prices[j]) {
                continue
            }
            let current_profit = prices[j] - buy
            if(current_profit > profit) {
                profit = current_profit
                
            }
        }
    }
    return profit
};
  1. 可以简化成:
var maxProfit = function(prices) {
    var lowestPrice = Infinity;
    var maxProfit = 0;
    
    for(let i=0; i<prices.length; i++){
        var currentPrice = prices[i];
        if(currentPrice < lowestPrice){
           lowestPrice = currentPrice;
           }else if(currentPrice - lowestPrice > maxProfit){
            maxProfit = currentPrice - lowestPrice 
        }
    }
    
    return maxProfit;
};

相关文章

网友评论

      本文标题:121. Best Time to Buy and Sell S

      本文链接:https://www.haomeiwen.com/subject/xwgqcqtx.html