Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III

问题:

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.

思路:

  动态规划

我的代码:

public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <= 1)    return 0;
        int size = prices.length;
        int[] left = new int[size];  
        int[] right = new int[size];
        int min = prices[0];
        int max = prices[size-1];
        int rst = 0;
        for(int i=1; i<size; i++)
        {
            min = Math.min(min,prices[i]);
            left[i] = Math.max(left[i-1],prices[i]-min);
        }
        for(int j=size-2; j>=0; j--)
        {
            max = Math.max(max,prices[j]);
            right[j] = Math.max(right[j+1],max-prices[j]);
        }
        for(int k=0; k<size; k++)
        {
            rst = Math.max(rst, left[k]+right[k]);
        }
        return rst;
    }
}
View Code

学习之处:

  • 对于动态规划的问题,也越来越有感觉了,也知道怎么找动态规划方程了,无非是逆向思维而已,但是有两种动态规划的方式还不太熟悉,如本题的这种渐进的方式left[i-1]<=left[i]<=left[i+1]如此下去求解出最优解 另外一种方式是全局的最优解是遍历所有局部最优解的最优解。
  • 对于想不出来的问题,应该考虑如下几个方面,是不是有规律?是不是可以分解成几个小的问题,进而递归求解或者动态规划求解?可不可以使用分治算法降低时间复杂度
  • 改掉坏习惯,生活,思考等

posted on 2015-04-27 20:35  zhouzhou0615  阅读(130)  评论(0编辑  收藏  举报

导航