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

Best Time to Buy and Sell Stock III

时间:2014-09-20 20:40:19      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:best time to buy and   leetcode   

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).

这个题的原型:http://blog.csdn.net/huruzun/article/details/39429631 利用动态规划思想,因为是最多两次交易,用一个数组记录左边每个位置profit 另外一个右边位置profit

数组l[i]记录了price[0..i]的最大profit,

数组r[i]记录了price[i..n]的最大profit。

已知l[i],求l[i+1]是简单的,同样已知r[i],求r[i-1]也很容易。

最后,我们再用O(n)的时间找出最大的l[i]+r[i],即为题目所求。

    public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int n = prices.length;
        int[] left = new int[n];
        int[] right = new int[n];
        int min = prices[0];
        for (int i = 1; i < n; i++) {
            left[i] = left[i - 1] > prices[i] - min ? left[i - 1] : prices[i] - min;
            min = min < prices[i] ? min : prices[i];
        }
        int max = prices[n - 1];
        for (int i = n - 2; i >= 0; i--) {
            right[i] = right[i + 1] > max - prices[i] ? right[i + 1] : max - prices[i];
            max = max > prices[i] ? max : prices[i];
        }
        int value = 0;
        for (int i = 0; i < n; i++) {
            value = value > left[i] + right[i] ? value : left[i] + right[i];
        }
        return value;
    }
}

Best Time to Buy and Sell Stock III

标签:best time to buy and   leetcode   

原文地址:http://blog.csdn.net/huruzun/article/details/39433187

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