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;
    };
  • 相关阅读:
    轻、快、好、免费的开发工具
    通过改进算法来优化程序性能的真实案例(Ransac)
    图像变形算法:实现Photoshop液化工具箱中向前变形工具
    用Helper对类的行为进行修饰以便复用(附:外三篇)
    桌边书
    高音+海豚音收藏
    Silverlight Framework没有得Enum.GetValues方法
    mysql安装出现error Nr.1045
    只有mdf文件而没有ldf文件修复方法
    js鼠标样式
  • 原文地址:https://www.cnblogs.com/shytong/p/5134809.html
Copyright © 2011-2022 走看看