【Leetcode】121. 最佳買賣股票的時間 I(Best Time to Buy and Sell Stock)

Leetcode - 121 Best Time to Buy and Sell Stock (Easy)

題目描述:最多交易一次。

解法一:DP

public int maxProfit(int[] prices) {
    if(prices == null || prices.length == 0) return 0;
    int[][] mp = new int[prices.length][3];
    mp[0][1] = -prices[0];
    int res = 0;
    for (int i = 1; i < prices.length; i++){
        mp[i][0] = mp[i - 1][0]; // 沒有買賣
        mp[i][1] = Math.max(mp[i - 1][1], mp[i - 1][0] - prices[i]); // 買了股票
        mp[i][2] = mp[i - 1][1] + prices[i]; // 賣了股票
        res = Math.max(res, Math.max(mp[i][0], Math.max(mp[i][1], mp[i][2])));
    }
    return res;
}

解法二:

public int maxProfit(int prices[]) {
    int minprice = Integer.MAX_VALUE;
    int maxprofit = 0;
    for (int i = 0; i < prices.length; i++) {
        if (prices[i] < minprice)
            minprice = prices[i];
        else if (prices[i] - minprice > maxprofit)
            maxprofit = prices[i] - minprice;
    }
    return maxprofit;
}
發佈了212 篇原創文章 · 獲贊 43 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章