zoukankan      html  css  js  c++  java
  • [leetcode-121-Best Time to Buy and Sell Stock]

    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.
    Example 1:
    Input: [7, 1, 5, 3, 6, 4]
    Output: 5
    max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
    Example 2:
    Input: [7, 6, 4, 3, 1]
    Output: 0
    In this case, no transaction is done, i.e. max profit = 0.

    开始思路很朴素:就是两个for循环然后比较最大值就行了。时间复杂度为O(n2).

    int maxProfit(vector<int>& prices)
        {
            if (prices.size() == 0)return 0;
            int localMax = 0;
            int globalMax = 0;
            for (int i = 0; i < prices.size();i++)//i买入
            {
                localMax = 0;
                for (int j = i + 1; j < prices.size();j++)//j卖出
                {
                    localMax = max(localMax, prices[j] - prices[i]);
                }
                globalMax = max(globalMax, localMax);
            }
            return globalMax;
        }

    然而。。。最后一个测试用例果然超时了。。

    然后学习一下大神的思路。受益匪浅。

    主要思想就是:

    这类问题相当于"max subarray problem",要using Kadane's Algorithm

    即计算当前值与前一个值的差,然后统计所有的差的和也即profit,如果profit为非负,那么可以保留,如果profit为负,

    说明加上当前值之后,总的profit就为负了,就不能保留当前值,得从下一个开始。即将profit置0。

    时间复杂度为O(n)。

    int maxProfit2(vector<int>& prices)
            {
                if (prices.size() == 0)return 0;
                int tempProfit = 0, maxProfit = 0;
                for (int i = 1; i < prices.size();i++)
                {
                    tempProfit += prices[i] - prices[i - 1];
                    tempProfit = max(0,tempProfit);
                    maxProfit = max(maxProfit,tempProfit);
                }
                return maxProfit;
        }

    参考:

    https://discuss.leetcode.com/topic/19853/kadane-s-algorithm-since-no-one-has-mentioned-about-this-so-far-in-case-if-interviewer-twists-the-input

    https://en.wikipedia.org/wiki/Maximum_subarray_problem

    http://www.algorithmist.com/index.php/Kadane's_Algorithm

  • 相关阅读:
    小菜鸟学 MQ(三)
    小菜鸟 学MQ(二)
    小菜鸟学 MQ(一)
    CXF 自定义拦截器
    WebService 入门程序(一)
    查找满足条件的颜色并替换
    jsfl 巧用获取jsfl绝对路径,导入配置文件,注意配置文件无法改变舞台宽高
    jsfl 发布保存关闭
    jsfl 改变舞台宽高
    AS3 在不规则区域内拖动
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6490021.html
Copyright © 2011-2022 走看看