zoukankan      html  css  js  c++  java
  • 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]如此下去求解出最优解 另外一种方式是全局的最优解是遍历所有局部最优解的最优解。
    • 对于想不出来的问题,应该考虑如下几个方面,是不是有规律?是不是可以分解成几个小的问题,进而递归求解或者动态规划求解?可不可以使用分治算法降低时间复杂度
    • 改掉坏习惯,生活,思考等
  • 相关阅读:
    事件DOMContentLoaded与load的区别
    JavaScript的执行环境
    JS中函数运行的执行次序
    正则表达式30分钟入门教程
    mysql数据库备份
    杂篇
    memcached
    mysql问题解决
    php学习
    apache 安装
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4461299.html
Copyright © 2011-2022 走看看