leetcode121 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 (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.
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Example 2:


中文題意

給定一個數組,其中存放每天的股票價格,在價格低的時候買進,價格高的時候拋出,才能獲利,求最大的利益(只能進行一次完整的買進-拋出交易)。


方法一

使用暴力遍歷法,即求數組中任意兩個元素的差值,然後找到這些差值的最大值。

class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i = 0; i < prices.length - 1; i++){
            
            for(int k = i+1; k<prices.length;k++){
                if(prices[i] - prices[k] >=0){
                    continue;
                }
                
                max = max > prices[k] - prices[i] ? max : prices[k] - prices[i];
            }
        }
        
        return max;
    }
}

在測試中,容易出現Time Limit Exceeded現象,時間複雜度爲O(n2)。


方法二

方法一在許多問題中都可以使用,方法二針對本問題,做一個優化。

方法一造成超時,是因爲對任意的兩個數字都做求差值計算,現在的優化是:獲得位置i上的元素,i位之前存在的最小值爲curmin,只需要計算第i位的元素和curmin的差值即可。同時profitmax變量存儲整個數組範圍內的最大利益值。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length ==0)
            return 0;
        
        int curmin = prices[0];//記錄當前位置之前的最小元素
        int curmax = 0;//當前位置的元素和當前最小元素的差值
        int profitmax = 0;//整個數組範圍內的最大利益值
        
        for(int i = 1; i < prices.length; i++){
            curmax = prices[i] - curmin;
            if(prices[i] < curmin)
                curmin = prices[i];
            if(curmax > profitmax)
                profitmax = curmax;
        }
        
        return profitmax;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章