码迷,mamicode.com
首页 > 其他好文 > 详细

Best Time to Buy and Sell Stock III

时间:2015-11-26 15:08:16      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:

题目:

Say you have an array for which the ith 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).

分析:把数组一分为二,正序求最大值并保存到一个数组,然后反序求最大值并保存到另一个数组,最后这两个数组相加求最终最大值即可。

代码(可参考Best Time to Buy and Sell Stock):

    public int maxProfit(int[] prices) {
        if(prices == null || prices.length == 0)
            return 0;
        int[] result1 = new int[prices.length];//保存正序扫描的最大收益
        int[] result2 = new int[prices.length];//保存反序扫描的最大收益
        int min = prices[0], max = prices[0];
        int result = 0;
        for (int i = 1; i < prices.length; i++) {//正序扫描
            if (prices[i] > max) { // 实时计算并保存最大收益
                max = prices[i];
                if (max - min > result) {
                    result = max - min;
                }
            } else if (prices[i] < min) { // 重新规定查找区域
                min = prices[i];
                max = prices[i];
            }
            result1[i] = result;
        }
        min = prices[prices.length-1]; max = prices[prices.length-1]; result = 0;
        for (int i = prices.length-2; i >= 0; i--) {//反序扫描
            if (prices[i] < min) { // 实时计算并保存最大收益
                min = prices[i];
                if (max - min > result) {
                    result = max - min;
                }
            } else if (prices[i] > max) { // 重新规定查找区域
                min = prices[i];
                max = prices[i];
            }
            result2[i] = result;
        }
        int max_profit = 0;
        for (int i = 0; i < prices.length; i++) {//叠加求和,输出最大值
            if (result1[i] + result2[i] > max_profit) {
                max_profit = result1[i] + result2[i];
            }
        }
        return max_profit;
    }

 

Best Time to Buy and Sell Stock III

标签:

原文地址:http://www.cnblogs.com/lasclocker/p/4997524.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!