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.

此题粗看一眼只要找到min和max就可以了,但是实际上有一个隐藏的条件,买的点min必须在卖的点max之前,我们可以每找到一个数把之后的元素全部遍历一边找到最大的数,但是那样是O(n^2)了。
实际上O(n)就可以解决,我们只需要在遍历一边的时候记录下当前发现的最小的值,然后计算最大值和更新最小值同时进行即可。

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length == 0)
            return 0;
        int min = prices[0];
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++)
        {
            if (prices[i]  maxProfit)
            {
                maxProfit = prices[i] - min;
            }
            
        }
        return maxProfit;
    }
}

Second Submission, just scan the prices once, compare the current value and the min value, update the max profit and min value accordingly

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length <= 1)
            return 0;
        int min = prices[0];
        int pro = 0;
        for (int i = 1; i < prices.length; i++) {
            pro = Math.max(pro, prices[i] - min);
            min = Math.min(prices[i], min);
        }
        return pro;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s