【leetCode】股票的最大利潤day12

題目

假設把某股票的價格按照時間先後順序存儲在數組中,請問買賣該股票一次可能獲得的最大利潤是多少?

 

示例 1:

輸入: [7,1,5,3,6,4]
輸出: 5
解釋: 在第 2 天(股票價格 = 1)的時候買入,在第 5 天(股票價格 = 6)的時候賣出,最大利潤 = 6-1 = 5 。
     注意利潤不能是 7-1 = 6, 因爲賣出價格需要大於買入價格。
示例 2:

輸入: [7,6,4,3,1]
輸出: 0
解釋: 在這種情況下, 沒有交易完成, 所以最大利潤爲 0。
 

限制:

0 <= 數組長度 <= 10^5

解題思路

  1. 首先理解題意,買入和賣出,差價肯定是後幾天和當天的差價。
  2. 所以我們計算出所有可能產生的差價,然後選出最大的一個。那就是最大利潤了

show me code

class Solution {
    public int maxProfit(int[] prices) {
        int i = 0;
        int nextMax =0;
        int max = 0;
//循環計算出所有可能性的差價
    for( i = 0; i< prices.length; i++){
        for(int j = i;j< prices.length-i;j++){
          nextMax =  prices[j] - prices[i];
         // 將最大的價格留下來,如果大於當前價格,那就替換。
          if(max < nextMax){
              max = nextMax; 
          }
        }
    }
    // 最後輸出最大價格
    return max;
    }
}
  1. 正確
class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1) {
            return 0;
        }
        int res = 0, min = prices[0];
        for(int i = 1; i < prices.length; i++) {
            if(prices[i] <= min) {
                min = prices[i];
            }else {
                res = Math.max(res, prices[i] - min);
            }
        }
        return res;
    }
}
  • 但是上面的思路在剛開始就錯了。
    如果我們再思考一下,如果說後一天的價格比今天的低那這豈不是後一天的利潤肯定比今天買入的低了。所以說根據這個思路,我們來理一下
class Solution {
    public int maxProfit(int[] prices) {
        if(prices== null || prices.length ==0){
            return 0;
        }
      //假設第一天的價格是最小的
        int min = prices[0];
       //初始化最大利潤
        int res = 0;
       // 遍歷查找最小的價格,計算最大利潤
        for (int i = 0; i<prices.length ;i++){
        //  後一天有價格低的肯定利潤比當前高
            if(min > prices[i]){
          // 將價格低的給設爲最小的
                min = prices[i];
            }else{
           // 計算使用最小价格計算最大利潤
                 res = Math.max(res ,prices[i] - min);
            }
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章