每周一算法2017.12.29

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.

描述:

股票买卖的最佳时机

假如你有一个数组,数组的第i个数表示股票在第i天的价格。

如果你只允许最多完成一个交易(即买入一个股票,卖出一份股票),设计一个最大利润的算法。

例1: 输入:[ 7, 1, 5,3, 6, 4 ] 输出:5

最大差异 = 6-1=5(不是7-1 = 6,销售价格必须大于购买价格) 例2: 输入:[ 7, 6, 4,3, 1 ] 输出:0

在这种情况下,不执行任何事务,即最大利润=0。

分析

一次循环即可。只需要找到最大增长即可。max(prices[j] – prices[i]) ,i < j

从前往后,用当前价格减去此前的最低价格,就是在当前点卖出股票能获得的最高利润。

循环中,更新最高利润和最低价格即可。

时间复杂度 空间复杂度

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

Java:

class Solution {  
    public int maxProfit(int[] prices) {

        int min = Integer.MAX_VALUE, 
        maxProfit = 0;
        for(int i = 0 ; i < prices.length; i++){
            if(prices[i]<min)  {
               min = prices[i];
            }
            if((prices[i]-min) > maxProfit) {
               maxProfit = prices[i] - min;
            }
        }
        return maxProfit;
    }
}

C++:

class Solution {  
public:  
    int maxProfit(vector<int>& prices) {

       if(prices.size() <= 1)  
            return 0;  

        int min = prices[0];  
        int maxProfit = 0;  

        for(int i = 1; i < prices.size(); i++)  {  
            int profit = prices[i] - min;  
            if(prices[i] < min) {
                min = prices[i];  
            }
            if(maxProfit < profit) {
                maxProfit = profit;  
              }
        }         
        return maxProfit; 
    }
};

Swift:

class Solution {  
    func maxProfit(_ prices: [Int]) -> Int {

        guard prices.count > 1 else { return 0 }
        var maxProfit = 0
        var min = prices[0]
        for i in 1 ..< prices.count {
            if min > prices[i] {
                min = prices[i]   
            }
             if prices[i] - min > maxProfit {
                maxProfit = prices[i] - min
            }
        }
        return maxProfit
    }
}

本题来自:leetCode

comments powered by Disqus