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

  • 相关阅读:
    Android游戏音效实现
    对Android体系结构的理解--后续会补充
    实现软件版本新特性的具体步奏
    搜索栏的自定义
    有关导航栏的相关认识
    自定义tabBar中的注意事项
    多控制器的管理
    ios中创建控制器的几种方式
    利用高德地图官方提供的API实现模拟定位的功能
    IOS中利用NSKeyedArchiver进行数据的归档和恢复
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6490021.html
Copyright © 2011-2022 走看看