zoukankan      html  css  js  c++  java
  • 【数组】Best Time to Buy and Sell Stock I/II

    Best Time to Buy and Sell Stock I

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    思路:

    只需要找出最大的差值即可,即 max(prices[j] – prices[i]) ,i < j。一次遍历即可,在遍历的时间用遍历low记录 prices[o....i] 中的最小值,就是当前为止的最低售价,时间复杂度为 O(n)。

    /**
     * @param {number[]} prices
     * @return {number}
     */
    var maxProfit = function(prices) {
        if(prices.length==0){
            return 0;
        }
        var n=prices.length,low=2147483647,ans=0;
        for(var i=0;i<n;i++){
            if(prices[i]<low){
                low=prices[i];
            }else if(prices[i]-low>ans){
                ans=prices[i]-low;
            }
        }
        
        return ans;
    };

    Best Time to Buy and Sell Stock I

    题目:

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    思路:

    此题和上面一题的不同之处在于不限制交易次数。也是一次遍历即可,只要可以赚就做交易。

    /**
     * @param {number[]} prices
     * @return {number}
     */
    var maxProfit = function(prices) {
        var n=prices.length,res=0;
        
        if(n==0){
            return 0;
        }
    
        for(var i=1;i<n;i++){
            if(prices[i]>prices[i-1]){
                res+=prices[i]-prices[i-1]
            }
        }
        
        return res;
    };
  • 相关阅读:
    jekins安装
    Nginx启动、关闭命令
    win10启动docker desktop报错
    CSS设置背景图片
    Lucene 8.5.2核心API
    Lucene 8.5.2演示API
    html+css实现选项卡效果
    搞懂JavaScript全局变量与局部变量,看这篇文章就够了
    你不知道的CSS妙用,纯CSS实现炫酷照片墙
    JS中!function(){}()的理解
  • 原文地址:https://www.cnblogs.com/shytong/p/5134809.html
Copyright © 2011-2022 走看看