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

  • 相关阅读:
    索引虚拟oracle virtual index
    用户盘云存储——百度网盘
    数据类型泛型的嵌套使用
    函数返回值C语言中malloc函数返回值是否需要类型强制转换问题
    控制文件oracle controlfile structure
    程序语言POJ 2406 Power Strings
    数组信息[置顶] php数组转换js数组操作及json_encode应用
    代码电话《程序员的第一年》情感编
    泛型通配符泛型中使用 通配符
    数字字符串一道有道实习生笔试算法题分析
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6490021.html
Copyright © 2011-2022 走看看