[leetcode] 123. 买卖股票的最佳时机 III

123. 买卖股票的最佳时机 III

暴力做法

直接枚举中间值,分成两个121. 买卖股票的最佳时机题做:

class Solution {
    public int maxProfitOne(int[] prices) {
        int min = Integer.MAX_VALUE;
        int ans = 0;

        for (int price : prices) {
            if (price < min) {
                min = price;
            } else if (ans < price - min) {
                ans = price - min;
            }
        }
        return ans;
    }

    public int maxProfit(int[] prices) {

        int ans = 0;
        for (int i = 0; i < prices.length; i++) {
            int[] left = new int[i];
            int[] right = new int[prices.length - i];
            System.arraycopy(prices, 0, left, 0, i);
            System.arraycopy(prices, i, right, 0, prices.length - i);
            ans = Math.max(ans, maxProfitOne(left) + maxProfitOne(right));
        }
        
        return ans;
    }
}

状态机(DP)

posted @ 2019-01-18 00:15  ACBingo  阅读(211)  评论(0编辑  收藏  举报