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

  • 相关阅读:
    php 之 没有mysql支持时的替代方案
    在php中使用sockets:从新闻组中获取文章
    PHP ON 阿里云的环境配置攻略
    java基础2
    java基础1
    连接查询(内连接)
    mysql数据约束
    mysql表中数据的增删改查2
    mysql表中数据的增删改查
    mysql表的增查改删
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6490021.html
Copyright © 2011-2022 走看看