劍指offer-20200322

20200322

題目 :股票的最大利潤

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

示例:

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

思路 :設置一個變量來存儲最小值,遍歷整個數組,利用當前值 - 最小值找到最大值,複雜度O(n)O(n)

code

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

code

使用某天i的最低歷史價格,狀態表示爲dp[i],狀態轉移方程爲dp[i]=min(dp[i-1],prices[i-1])

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

題目:求1+2+…+n,要求不能使用乘除法,for、while、if、else、switch、case等關鍵字及條件判斷語句(A?B:C)。

示例

輸入: n = 3
輸出: 6
class Solution{
    public int sumNums(int n){
		boolean b = (n==0) || ((n+=sumNums(n-1))>0);
    }
    return n;
}

class Solution{
    public int sumNums(int n){
        boolean b = (n>0) && ((n+=sumNums(n-1))>0);
    }
    return n;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章