leetcode121 Best Time to Buy and Sell Stock

来源:互联网 发布:mac文本编辑器 编辑:程序博客网 时间:2024/06/10 03:30

我的github:https://github.com/gaohongbin/leetcode

题目:

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.

Subscribe to see which companies asked this question

翻译:

给定一个数组,其中第i个元素表示股票在第i天的价格。

如果只能完成一次交易,请设计一个算法算出能获取的最大利润。

思路:

(1)一般会想到最基本的方法,每次选择一个prices[i]作为买入价格,遍历后面所有的prices[]元素,记录最高利润。这个时间复杂度O(n*n).

(2)另一种时间复杂度为O(N)的算法。

这个题不能理解为找最小数min和最大数max,然后用max-min就是结果,这样理解是错误的,因为一个数组的最下数min很有可能在最大数max后面,但实际情况不可能是我们先卖然后再买,所以这个题应该是找两个数,使得后面一个数减去前一个数,使相差结果最大。

设prices[]的值为ABCDEFGHIJK如果我们A是我们的买入价格,如果BCDEFGHIJK里面有大于A的数(假设为F),这个数我们可以直接忽略,因为如果卖出价格在F后面,则明显以A买入利润更高。

如果BCDEFGHIJK里面有个数小于A(假设还是F),在遍历到F之前,maxProfit存的是卖出价在BCDE之间时的最大利润。

遍历到F时,我们把price=F,因为F有可能是我们需要寻找的买入价格。但这不确定因为如果是2,6,1,4则明显6-2是最好的选择。

我们现在要检测是选A好还是选择F好,如果卖出价格在F之后,那么F是更好的买入价格,所以就要在BCDE和GHIJK中找到一个最好的卖出价,遍历到F之前,利润maxProfit是存在于prices[i]-price,遍历到F之后,最大利润maxProfit存在于prices[i]-F。

代码:

public int maxProfit(int[] prices) {          int length=prices.length;        if(prices==null || length<2)        return 0;                int price=prices[0];        int maxProfit=0;        for(int i=0;i<length;i++){        if(prices[i]-price>maxProfit)        maxProfit=prices[i]-price;        if(prices[i]<price)        price=prices[i];        }        return maxProfit;    }


0 0
原创粉丝点击