Amazon-Best Time to Buy and Sell Stock (Easy)

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Solution:

    public int maxProfit(int[] prices) {
        if(prices==null || prices.length==0) return 0;
        int buy=prices[0];
        int max=0;
        
        for(int i=1;imax){
                max=prices[i]-buy;
            }
            if(prices[i]

时间复杂度:O(n)
空间复杂度:O(1)

一开始只想到了遍历两次求所有卖出利润最大,但是肯定不会让人满意,复杂度是O(n^2)。后来发现其实不用每一个都求,只要按天求卖出利润最大就行了,之后如果该天数值比之前买的小,则改为在今天买入。这个思路其实不难理解,由于题目中说明求一次交易的最大值,且不能先卖后买,是有次序的,所以只要在遍历中记录买入值(确保是遇到的最小的数),然后在下一天求出差值,和最大值进行比较就可以了。或许有人(我)会担心改变了买入值,万一之后的最大值max不是真的最大值呢?其实并不是这样的,如果后面的值比改变买入值之前的值还要大,那么改变后的买入值肯定是利益最大的,因为改变后的买入值变小了。如果后面的值和买入值差值不比原来的差值max还大,说明之前的max值是正确的。

你可能感兴趣的:(Amazon-Best Time to Buy and Sell Stock (Easy))