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

  • 相关阅读:
    【Python】使用codecs模块进行文件操作及消除文件中的BOM
    Vue公共结果页面实现
    vscode调整字体大小
    vue-cli3使用vue-svg-loader加载svg
    Microsoft Edge Chrome 下载
    [译]基于Vue.js的10个最佳UI框架,用于构建移动应用程序
    axios采坑之路
    MacBook Touch Bar 使用技巧
    vue-cli 3.x 移除console总结
    嵌入式Linux如何设置获取uboot参数
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6490021.html
Copyright © 2011-2022 走看看