文章标题

来源:互联网 发布:centos7 nginx 访问 编辑:程序博客网 时间:2024/06/05 09:22

LeetCode 121

Best time to buy and sell stock

  1. 问题描述:
    Say you have an array for which the i th 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.
    题目解说:
    给出一个数组,数组中包含的是第i天股票价格,可以以当天这个买入或者卖出,给出一个算法,使得买入和卖出的差值最大进而使得获利最大。

2.题目思路:
开始使用的两层循环,外层控制买入,内层控制卖出,找到最大差值,但是运行发现超时了;所以O(n^2)的时间复杂度是不允许的。因此需要找到用一层循环就能解决问题的方法。
此处介绍一种算法Kadane’s Algorithm,不懂的同学看此处链接:(https://en.wikipedia.org/wiki/Maximum_subarray_problem);
获取当前最大利润有两种情况:
1. maxCurr += prices[i] - prices[i-1]; i-1天时的最大利润-i-1那天的价格+当前股票价格;
2. 当卖出-买入价格一直处于亏损,也就是负值状态时,返回0;

3.理解maxCurr += prices[i] - prices[i-1];
比如当前为第三天,那么 maxCurr = prices[2] - price[1] + prices[3] - price[2] = prices[3] - prices[1];在循环中,得到的是当前利润,通过 Math.max(0, maxCurr += prices[i] - prices[i-1]); 得到当前利润;当前利润,找出当前利润最大值:maxSoFar= Math.max(maxCurr, maxSoFar);进而返回maxSoFar。

Java版:时间复杂度O(n)

class Solution {    public int maxProfit(int[] prices) {        int maxCurr= 0;        int maxProfit = 0;        for(int i =1; i<prices.length; i++){            maxCurr = Math.max(0, maxCurr += prices[i]-prices[i-1]);            maxProfit = Math.max(maxCurr,maxProfit);        }        return maxProfit;    }注意:maxProfit 和maxCurr都必须设置为0,因为当持续亏损时,返回0.

持续刷题,更新中···