LeetCode每日一题:买卖股票的最好时机 3

问题描述

Say you have an array for which the i element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

问题分析

相比于上一题,股票一共只能买卖两次,我们可以采用分治算法,把price数组分成[o,i][i,price.length]两段,再在每段上用上一题的算法求最大收益,最后再算一次总体的,取其中最大值即可。

代码实现

public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 0; i < prices.length; i++) {
            int profit1 = 0;
            int profit2 = 0;
            for (int j = 0; j <= i; j++) {
                for (int k = j + 1; k <= i; k++) {
                    profit1 = Math.max(profit1, prices[k] - prices[j]);
                }
            }
            for (int j = i + 1; j < prices.length; j++) {
                for (int k = j + 1; k < prices.length; k++) {
                    profit2 = Math.max(profit2, prices[k] - prices[j]);
                }
            }
            profit = Math.max(profit, profit1 + profit2);
        }
        return profit;
    }

你可能感兴趣的:(LeetCode每日一题:买卖股票的最好时机 3)